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

7

我需要编写业务逻辑,需要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.
            };
        }

参考资料:为什么使用依赖注入 https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#ASP0000


https://stackoverflow.com/a/68510106/5298150 - abdusco
1个回答

14

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接