且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP .NET MVC 5 6 3身份角色声明组

更新时间:2023-02-26 07:42:29

我们在这里同一条船上,没有太多的从课程的源读取方面除了...

We were in the same boat here, without much in terms of reading apart from the source of course...

我们结束了执行政策。所需要的授权策略是一组权利要求得到满足。那么这些策略可以应用到控制器。

We ended up implementing Policies. Policies being a group of Claims that are required for authorization to be satisfied. these Policies can then be applied to Controllers.

您可以在Startup.cs定义你的政策,ConfigureServices:

You can define your Policies in Startup.cs, ConfigureServices:

services.AddAuthorization(options =>
{
    options.AddPolicy("SalesSenior", policy =>
    {
        policy.RequireClaim("department", "sales");
        policy.RequireClaim("status", "senior");
    });
});

我们定义的角色,分配1个或多个声明,对他们分配到的角色让他们反对击中控制器相应的策略来检查用户。

We defined Roles, assigned 1 or more Claims to them and assigned Roles to Users allowing them to be checked against the appropriate Policy on hitting a Controller.

您可以注入 IAuthorizationService 成控制器或属性像这样:

You can inject the IAuthorizationService into a Controller or Attribute as so:

public class SalesDashboardController: Controller
{
    private readonly IAuthorizationService _authz;

    public VarianceOverviewController(IAuthorizationService authz)
    {
        _authz = authz;
    }
    ...
}

您可以再使用 IAuthorizationService 来检查用户的要求是否正当...

You can then use the IAuthorizationService to check the validity of a users claims...

if (await _authz.AuthorizeAsync(User, "SalesSenior"))
{
    // User is authorized            
}

这篇文章是我这个东西主要来源,对我来说是一个伟大的底漆。祝你好运!

This article was my main source for this stuff and was a great primer for me. Good luck!