How to inject services in an AddOpenIdConnect event (OnTokenValidated)?
Asked Answered
P

1

8

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

Promptbook answered 27/7, 2021 at 15:33 Comment(1)
P
18

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
    }
}
Pesthouse answered 27/7, 2021 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.