动态添加角色以授权ASP.NET 5中控制器的属性 [英] Dynamically add roles to authorize attribute for controller in ASP.NET 5
问题描述
我对此帖子有一个示例问题动态添加角色以进行授权的属性,但对于ASP.NET 5(vNext) 在ASP.NET 5中,如上面的帖子所述,我无法覆盖AuthorizeAttribute类.那么如何在ASP.NET 5(vNext)中动态添加角色控制器
I have a sample question with this post Dynamically add roles to authorize attribute for controller but for ASP.NET 5 (vNext) In ASP.NET 5, I can not overwrite AuthorizeAttribute class as above post said. So how can I add roles dynamically Controllers in ASP.NET 5 (vNext)
提前谢谢.
推荐答案
正如迈克所说,您需要策略.这是一个实现.
As mike mentioned, you need policies. Here is one implementation.
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
protected override void Handle(Microsoft.AspNet.Authorization.AuthorizationContext context, CustomRoleRequirement requirement)
{
var roles = new[] { "Admin", "Admin2", "Admin3" }; //Get From DB.
var userIsInRole = roles.Any(role => context.User.IsInRole(role));
if (!userIsInRole)
{
context.Fail();
return;
}
context.Succeed(requirement);
}
}
并在startup.cs中的ConfigureServices方法中
And in the ConfigureServices method in startup.cs
services.ConfigureAuthorization(options =>{
options.AddPolicy("CustomRole", policy => policy.AddRequirements(new CustomRoleRequirement()));
});
并且您需要像这样在控制器中提供autorize属性.
And you need to provide the autorize attribute in the controller like this.
[Authorize(Policy = "CustomRole")]
来源: https://forums.asp.net/post/5975557.aspx
希望有帮助.
这篇关于动态添加角色以授权ASP.NET 5中控制器的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!