Search code examples
c#asp.net-coreidentityserver4duende-identity-server

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


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


Solution

  • 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
        }
    }