Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve dependencies for authentication event handler through 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>() 
       );  
    });     
like image 592
Frank Avatar asked Dec 23 '22 04:12

Frank


1 Answers

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.

like image 93
poke Avatar answered Jan 11 '23 23:01

poke