如何在OIDC中间件中访问DBContext

huangapple go评论97阅读模式
英文:

.NET How to access the DBContext within OIDC Middleware

问题

我有以下的 Startup.cs 中的 #ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => { Configuration.Bind("AzureAd", options); });
    
    // 注册 TracingContext 以访问数据库
    services.AddDbContext<TracingContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    });

    services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
    {
        options.Events = new OpenIdConnectEvents
        {
            OnTokenValidated = ctx =>
            {
                // 获取用户的电子邮件
                var email = ctx.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

                // 如何从上面访问 TracingContext?
                // 在这里编写代码

                // 添加声明
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Role, "HQUser")
                };
                var appIdentity = new ClaimsIdentity(claims);

                ctx.Principal.AddIdentity(appIdentity);

                return Task.CompletedTask;
            },
        };
    });
}

由于我在方法中使用 services.AddDbContext(...) 定义了 TracingContext(DBContext),在 OICD 中间件中如何访问 TracingContext?

我需要在这一点上从数据库中检索用户的角色。

谢谢

英文:

I have the following Startup.cs #ConfigureServices method:

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options =&gt; { Configuration.Bind(&quot;AzureAd&quot;, options); });
        
        //Register TracingContext to access the DB
        services.AddDbContext&lt;TracingContext&gt;(options =&gt;
        {
            options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;));
        });

        services.Configure&lt;OpenIdConnectOptions&gt;(AzureADDefaults.OpenIdScheme, options =&gt;
        {
            options.Events = new OpenIdConnectEvents
            {
                OnTokenValidated = ctx =&gt;
                {
                    // Get the user&#39;s email 
                    var email = ctx.Principal.Claims.FirstOrDefault(c =&gt; c.Type == ClaimTypes.Name)?.Value;

                    // Query the database to get the role
                    **// BUT: How do I access the TracingContext from above?** 
                    **// CODE HERE **
                    
                    // Add claims
                    var claims = new List&lt;Claim&gt;
                    {
                        new Claim(ClaimTypes.Role, &quot;HQUser&quot;)
                    };
                    var appIdentity = new ClaimsIdentity(claims);

                    ctx.Principal.AddIdentity(appIdentity);

                    return Task.CompletedTask;
                },
            };
        });
    }

Since I have defined the TracingContext (DBContext) in the method by using services.AddDbContext(...), how can I access the TracingContext in the OICD MiddleWare?

I need to retrieve the User's role from the database at this point.

Thank you

答案1

得分: 1

你可以使用 HttpContext.RequestServices.GetRequiredService 来获取依赖项:

var db = ctx.HttpContext.RequestServices.GetRequiredService<YourDbContext>();
英文:

You can use HttpContext.RequestServices.GetRequiredService to get the dependency :

var db = ctx.HttpContext.RequestServices.GetRequiredService&lt;YourDbContext&gt;();

huangapple
  • 本文由 发表于 2020年1月3日 15:07:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定