我有一个像这样的AuthorizationRequirement
类-
internal class ClaimsRoleRequirement : IAuthorizationRequirement
{
private readonly EClaim eClaimValue;
public ClaimsRoleRequirement(object claimValue)
{
eClaimValue = (EClaim)claimValue;
//name = eClaimValue.ToString();
//description = eClaimValue.Description();
}
}
我从Startup.cs
文件这样调用这个-
public void ConfigureServices(IServiceCollection services)
{
..................
..................
services.AddAuthorization(options => {
foreach (object eClaimValue in Enum.GetValues(typeof(EClaim)))
{
options.AddPolicy(eClaimValue.ToString(), policy => policy.Requirements.Add(new ClaimsRoleRequirement(eClaimValue)));
}
});
}
我喜欢在ClaimsRoleRequirement
类中查询DB并从会话中获取当前用户。有办法做到这一点吗?
Re-
EClaim
枚举如下-
public enum EClaim
{
[Display(Name = "Role-Claim Policy")]
[Description("Role-Claim-View")]
RoleClaimView = 0,
[Description("Role Create")]
RoleCreate,
[Description("Claim Create")]
ClaimCreate
}
我的数据库上下文是这样的-
public class ApplicationDbContext : IdentityDbContext<User, Role, Guid, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
private string IdentitySchemaName = "Identity";
private readonly IWebHostEnvironment Environment;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IWebHostEnvironment env)
: base(options)
{
Environment = env;
//this.Database.EnsureCreated();
}
........
........
}
在您的案例中,授权要求ClaimsRoleRequirement
只是一种标记,指定用户访问资源需要此要求。但是,要求的工作不是指定如何为用户验证此要求。
要评估需求,您需要为您的需求创建一个授权处理程序。然后,当授权系统评估需求时,将调用授权,并且处理程序有机会评估它。作为该过程的一部分,处理程序还可以访问特定于请求的信息,例如来自会话的信息,或者查询其他服务以检索进一步的信息。
例如,您的需求的处理程序可能如下所示:
public class ClaimsRoleAuthorizationHandler : AuthorizationHandler<ClaimsRoleRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ClaimsRoleAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ClaimsRoleRequirement requirement)
{
var user = context.User;
var httpContext = _httpContextAccessor.HttpContext;
var session = httpContext.Session;
var db = httpContext.RequestServices.GetService<ApplicationDbContext>();
// do stuff
// finally, call Succeed for the requirement if the user fulfills the requirement
context.Succeed(requirement);
}
}
也就是说,在使用ASP.NET Core Identity时,如果您只想验证角色或身份的自定义声明,则不需要往返数据库来验证这些要求。您身份的已配置角色将自动添加为角色声明,您为应用程序用户配置的自定义声明也将在声明主体上可用。因此,您应该能够通过执行context.User.IsInRole(roleName)
或context.User.HasClaim(claimType)
之类的操作来验证这些。