如何在 AddOpenIdConnect 事件 (OnTokenValidated) 中注入服务?

Abh*_*eet 7 c# asp.net-core identityserver4 duende-identity-server

我需要编写需要ConfigureServices完全执行的业务逻辑。 OnTokenValidated本身的位置很糟糕ConfigureServices

中间件的替代方案是什么AddOpenIdConnect,以便我可以 Success完全灵活地调用以使用注入的服务?

        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.
            };
        }
Run Code Online (Sandbox Code Playgroud)

参考:为什么 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#ASP0000

abd*_*sco 16

要解析OnTokenValidated事件处理程序内的服务,您可以使用TokenValidatedContext.HttpContext.RequestServices

Events =
{
    OnTokenValidated = async context =>
    {
        var someService = context.HttpContext.RequestServices.GetRequiredService<ISomeService>();
        var result = await someService.DoSomethingAsync();
        // a custom callback
    }
}
Run Code Online (Sandbox Code Playgroud)