我们是否可以访问dbcontext以在自定义的基于策略的授权中获取表数据和会话?任何人都可以帮助如何实现它?
services.AddAuthorization(options =>
{
options.AddPolicy("CheckAuthorize",
policy => policy.Requirements.Add(new CheckAuthorize()));
});
services.AddSingleton<IAuthorizationHandler, CheckAuthorize>();
public class CheckAuthorize : AuthorizationHandler<CheckAuthorize>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CheckAuthorize requirement)
{
if () //check session to verify user is logged in or not
{
//redirect to login page
}
else
{
if ()//access dbcontext get data from database table to validate user access
{
//redirect to access denied page
}
}
throw new NotImplementedException();
}
}
答案 0 :(得分:10)
政策可以使用DI
因此,假设您的数据库上下文在DI中,您可以执行类似
的操作public class CheckAuthorizeHandler : AuthorizationHandler<CheckAuthorizeRequirement>
{
MyContext _context;
public CheckAuthorizeHandler(MyContext context)
{
_context = context;
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
MyRequirement requirement)
{
// Do something with _context
// Check if the requirement is fulfilled.
return Task.CompletedTask;
}
}
请注意,当你这样做时,你必须让你的要求成为一个单独的课程,你不能CheckAuthorize : AuthorizationHandler<CheckAuthorize>, IAuthorizationRequirement
,所以你必须这样做
public CheckAuthorizeRequirement : IAuthorizationRequirement
{
}
最后,您需要在DI系统中注册您的处理程序
services.AddTransient<IAuthorizationHandler, CheckAuthorizeHandler>();