简体   繁体   English

在.NET Core MVC中,如何在AuthorizationHandler中访问DbContext?

[英]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.

相关问题 如何从 AuthorizationHandler .NET Core 获取参数 - How to get params from AuthorizationHandler .NET Core .NET Core 6 程序 class builder.Build() 后如何访问 DbContext class? - How do I access DbContext class in .NET Core 6 program class after builder.Build()? .Net Core:如何初始化需要 DBContext 的单例? - .Net Core: How do I initialize a singleton that needs a DBContext? 如何使用.Net Core 2.1配置依赖项注入的DbContext? - How do I configure a DbContext with dependency injection with .Net Core 2.1? 在ASP.NET核心中使用时,如何从另一个项目访问EF核心的DbContext? - How to I access the DbContext of EF core from another project when used in ASP.NET core? .NET Core AuthorizationHandler 失败 - 如何路由到新页面 - .NET Core AuthorizationHandler fails - how to route to a new page 如何在ASP.NET MVC Core中获取瞬态DbContext? - How to get transient DbContext in ASP.NET MVC Core? 如何访问 asp.net 核心服务的 DbContext - How to access the DbContext fom asp.net core service 如何在ASP.NET Core MVC应用程序中访问命令行参数? - How do I access command line parameters in an ASP.NET Core MVC app? 我应该如何在MVC Core中管理DbContext Lifetime? - How should I manage DbContext Lifetime in MVC Core?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM