该应用程序是在asp.net核心3上开发的。当用户具有多个角色时,面临授权问题。
用户角色:
public enum UserRole
{
None = 0x0,
View = 0x1,
ConfirmAlarm = 0x2,
ObjectScaling = 0x4,
SchemeEditor = 0x8,
ObjectEditor = 0x10
}
索赔
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
new Claim(ClaimsIdentity.DefaultRoleClaimType, ((UserRole)user.Role).ToString()),
new Claim("uGroupId", user.GroupId.ToString()),
new Claim("uInfo", user.Info),
new Claim("uTheme", user.Theme)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie",
ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new
ClaimsPrincipal(id));
}
控制器方法:
[Authorize(Roles = "View")]
[HttpPost("[action]")]
public async Task<string> SomeAction()
{
//...some code
}
如果用户具有“视图,ConfirmAlarm,ObjectScaling,SchemeEditor,ObjectEditor”的所有角色,则无法在控制器中授权该方法。
可能是什么问题?需要创建自定义AuthorizeAttribute吗?
请尝试以下行:
ClaimsIdentity id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme,
ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
而不是:
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie",
ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
[CookieAuthenticationDefaults.AuthenticationScheme
是Cookies
,它匹配Startup.cs
中cookie的默认authenticationScheme:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
已更新:
您可以手动检查声明:
services.AddAuthorization(options =>
{
options.AddPolicy("AllowedView", policy =>
{
policy.RequireAssertion(context =>
{
var roles = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value;
var listRolesElements = roles.Split(',').ToList();
return listRolesElements.Contains("View");
});
});
});
并在需要View
权限的控制器上应用策略:
[Authorize(Policy = "AllowedView")]