Resolve dependencies for authentication event handler through DI

蹲街弑〆低调 提交于 2021-01-23 06:17:49

问题


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>() 
       );  
    });     

回答1:


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.

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.



来源:https://stackoverflow.com/questions/52468816/resolve-dependencies-for-authentication-event-handler-through-di

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!