通过DI解决身份验证事件处理程序的依赖项 [英] Resolve dependencies for authentication event handler through DI

查看:50
本文介绍了通过DI解决身份验证事件处理程序的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JWT承载令牌来保护我的ASP.NET Core 2.1 Web API.在 ConfigureServices 期间,我设置了身份验证,并通过选项绑定了 JwtBeaererEvents 对象,以进行其他处理.我希望该对象成为DI容器的一部分,但是我不确定如何做到这一点.现在,我必须创建实例并将其通过构造函数(反模式)传递.但这将创建一个鸡加蛋的场景:

I use JWT bearer tokens to protect my ASP.NET Core 2.1 web API. During ConfigureServices, I setup the authentication, and tie in a JwtBeaererEvents object via options for additional processing. I'd like this object to be part of the DI container but I'm not sure how to do that. For now, I have to create instances and pass it through the constructor (anti-pattern). But this is going to create a chicken and an egg scenario:

/* HACK */
var sp = services.BuildServiceProvider();

services.AddAuthentication(opts =>
{
    opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(opts =>
{                
    opts.Audience = "https://foobar.com/FooAPI";
    opts.Authority = Constants.AuthEndpointPrefix + "common/";
    opts.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };

    /* I would like JwtBearerEvents to be part of the 
       DI container and request the Logger and AppInsights 
       Dependency through the ctor 
    */
    opts.Events = new 
       JwtBearerEvents(
          LoggerFactory.CreateLogger<JwtBearerEvents>(),
          sp.GetService<TelemetryClient>() 
       );  
    });     

推荐答案

ASP.NET Core 2中的身份验证系统使用

The authentication system in ASP.NET Core 2 supports this natively using the EventsType property of the authentication scheme options:

services.AddTransient<MyJwtBearerEvents>();
services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.EventsType = typeof(MyJwtBearerEvents);
    });

如果设置了此属性,则在请求开始时初始化身份验证方案时,事件实例将得到解析.

If this property is set, then the events instance will get resolved when the authentication scheme is being initialized at the beginning of the request.

除此之外,请注意,您还可以访问作为事件上下文的一部分传递的 HttpContext 实例,并使用服务定位器模式来解析事件处理程序中的服务.虽然通常不是最好的服务定位器,但是如果您只需要为特定事件类型提供一些依赖关系,那么在这种情况下,它可以为您提供更多的灵活性.

Apart from this, note that you could also access the HttpContext instance that gets passed as part of the event contexts, and use the service locator pattern to resolve services inside of your event handlers. While using the service locator is generally not the best idea, it can give you a bit more flexibility in this case, if you require some dependencies just for a particular event type.

这篇关于通过DI解决身份验证事件处理程序的依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆