如何在.net core 2中设置deaful Authorization

时间:2018-02-11 11:32:34

标签: asp.net-core asp.net-core-2.0

我正在使用这样的自定义要求:

    services.AddAuthorization(options => {
        options.AddPolicy("MyAuthorizationRequirement",policy => {
            policy.Requirements.Add(new MyRequirement());
        });
    });

我希望能够在我的控制器上设置[Authorize]属性并使用自定义授权方法。

但是根据我设定的自定义要求,我必须使用[Authrization(" MyAuthorizationRequirement")]

如何设置某种默认值才能使用单个属性?

2 个答案:

答案 0 :(得分:1)

让我试着解释一下这里需要什么。

services.AddAuthorization的作用是,它尝试配置授权。在首先配置授权之前,需要配置身份验证。对于ConfigureServices方法中的那个,您可以执行类似的操作。

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => 
    {
        options.Audience = "http://localhost:5001/";
        options.Authority = "http://localhost:5000/";
    });

现在你可以配置,

services
    .AddAuthorization(options =>
    {
        options.AddPolicy("PolicyName", policy => policy.RequireClaim("SomeClaimName"));
        // you can configure your requirement above in various ways, you might want to check those out
    });

最后是Configure方法,

app.UseAuthentication();

现在在控制器中,

// [Authorize("PolicyName")]
// If you have above in your controllers/actions, those will only be accessible to users who has "SomeClaimName"

// [Authorize]
// Those who are authenticated, can access these endpoints

答案 1 :(得分:0)

您可以创建一个继承自AuthorizeAttribute

的新类
public class MyAuthorizationAttribute : AuthorizeAttribute
{
    public MyAuthorizationAttribute()
        : base("MyAuthorizationRequirement")
    {
    }
}

并在您的控制器上使用[MyAuthorization]