查询数据库以获取ASP.NET Core中的每个操作之前的角色授权
与核心相结合的ASP.NET Core已经提供了一种简单的方法来在登录后检查角色,但是我希望在每个控制器操作之前向数据库查询当前用户的当前角色。
我已阅读了微软基于角色,基于策略和基于声明的授权。 (https://docs.microsoft.com/en-us/aspnet/core/security/authorization/introduction)这些解决方案似乎都不会检查每个操作的角色。 这是我最近尝试以某种基于政策的授权的形式实现期望的结果:
在Startup.cs中:
DatabaseContext context = new DatabaseContext();
services.AddAuthorization(options =>
{
options.AddPolicy("IsManager",
policy => policy.Requirements.Add(new IsManagerRequirement(context)));
options.AddPolicy("IsAdmin",
policy => policy.Requirements.Add(new IsAdminRequirement(context)));
});
在我的需求文件中:
public class IsAdminRequirement : IAuthorizationRequirement
{
public IsAdminRequirement(DatabaseContext context)
{
_context = context;
}
public DatabaseContext _context { get; set; }
}
public class IsAdminHandler : AuthorizationHandler<IsAdminRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsAdminRequirement requirement)
{
// Enumerate all current users roles
int userId = Int32.Parse(context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value);
Roles adminRoles = requirement._context.Roles.FirstOrDefault(r => r.Name == "Administrator" && r.IsActive == true);
bool hasRole = requirement._context.UserRoles.Any(ur => ur.UserId == userId && adminRoles.Id == ur.RoleId && ur.IsActive == true);
// Check for the correct role
if (hasRole)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
并在控制器中:
[HttpGet]
[Authorize(Policy = "IsAdmin")]
public async Task<IActionResult> Location()
{
// do action here
}
有了这些代码,需求中间件从未被调用,因此数据库从不被检查。
在执行每个控制器操作之前,如何正确地查询数据库以检查当前用户的角色?
链接地址: http://www.djcxy.com/p/90187.html上一篇: Query Database for Role Authorization Before Each Action in ASP.NET Core
下一篇: based Authorization for multiple Claims in Asp.net Core