[英]In .NET Core MVC, how do I access the DbContext while inside an AuthorizationHandler?
Here is my startup code to configure services: 这是我的配置服务的启动代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ThisApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAuthentication(
SharedOptions => SharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
services.AddAuthorization(
options => { options.AddPolicy("ValidUsers",
policy =>
{
policy.Requirements.Add(new ValidUserAuthorization());
});
});
}
And here is the class for authorizing users: 这是授权用户的类:
public class ValidUserAuthorization : AuthorizationHandler<ValidUserAuthorization>, IAuthorizationRequirement
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserAuthorization requirement)
{
string username = context.User.Identity.Name;
if (context.User.Identity.Name == "hardcoded-username")
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
I would like to change my authorization class ( ValidUserAuthorization
) to be able to look up the username in my application database (as accessed via ThisApplicationDbContext
), rather than comparing against hard-coded strings. 我想更改我的授权类(
ValidUserAuthorization
),以便能够在我的应用程序数据库中查找用户名(通过ThisApplicationDbContext
访问),而不是与硬编码字符串进行比较。
What is the best way of obtaining this database context (as already initialized in ConfigureServices
) and having the authorization class use it? 获取此数据库上下文(已在
ConfigureServices
初始化)并让授权类使用它的最佳方法是什么?
One possible way of doing it is by passing the type of your DbContext as a generic type: 一种可行的方法是将DbContext的类型作为泛型类型传递:
public class ValidUserAuthorization<TDbContext> : AuthorizationHandler<ValidUserAuthorization>, IAuthorizationRequirement
where TDbContext : DbContext, new()
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserAuthorization requirement)
{
using (TDbContext db = new TDbContext())
{
// ...
}
}
}
Then you can create the ValidUserAuthorization
object like this in your ConfigureServices
method: 然后,您可以在
ConfigureServices
方法中创建如下的ValidUserAuthorization
对象:
policy.Requirements.Add(new ValidUserAuthorization<ThisApplicationDbContext>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.