5

I need to write and business logic which requires ConfigureServices to get fully executed. OnTokenValidated is badly located with-in ConfigureServices itself.

What is the alternative of AddOpenIdConnect middleware so that I can Success call with full flexibility to use injected services?

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "cookie";
            //...
        })
        .AddOpenIdConnect("oidc", options =>
        {
            options.Authority = "https://localhost:5001";
            /....
            options.Scope.Add("offline_access");

            options.Events.OnTokenValidated = async n =>
            {
                //Need other services which will only 
                //get injected once ConfigureServices method has fully executed.
            };
        }

Reference: Why https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#ASP0000

abdusco
  • 9,700
  • 2
  • 27
  • 44
Abhijeet
  • 13,562
  • 26
  • 94
  • 175

1 Answers1

11

To resolve services inside the OnTokenValidated event handler, you can use TokenValidatedContext.HttpContext.RequestServices:

Events =
{
    OnTokenValidated = async context =>
    {
        var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
        var result = await someService.DoSomethingAsync();
        // a custom callback
    }
}
abdusco
  • 9,700
  • 2
  • 27
  • 44