我正在使用这样的自定义要求:
services.AddAuthorization(options => {
options.AddPolicy("MyAuthorizationRequirement",policy => {
policy.Requirements.Add(new MyRequirement());
});
});
我希望能够在我的控制器上设置[Authorize]
属性并使用自定义授权方法。
但是根据我设定的自定义要求,我必须使用[Authrization(" MyAuthorizationRequirement")]
如何设置某种默认值才能使用单个属性?
答案 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]
。