gpt4 book ai didi

c# - 如何在使用依赖注入(inject)的 ASP.NET Core 2 中使用 OIDC 登录到 Azure AD 后添加自己的声明?

转载 作者:行者123 更新时间:2023-11-30 17:32:49 25 4
gpt4 key购买 nike

在 ASP.NET Core 2 中登录 Azure AD 相当简单,在 ConfigureServices(IServiceCollection services) 中只需添加以下内容

// Azure AD login
services.AddAuthentication(a =>
{
a.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
a.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
a.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(o => o.LoginPath = new PathString("/Account/SignIn"))
.AddOpenIdConnect(o =>
{
o.ClientId = Configuration["Authentication:AzureAd:ClientId"];
o.ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"];
o.Authority = Configuration["Authentication:AzureAd:AADInstance"] +
Configuration["Authentication:AzureAd:TenantId"];
o.CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"];
o.ResponseType = OpenIdConnectResponseType.CodeIdToken;
o.Events = new OpenIdConnectEvents
{
OnRemoteFailure = RemoteFailure,
OnTokenValidated = TokenValidated
};
});

一切正常。然后我可以在 TokenValidated 中添加 Claims 并且效果也很好:

private Task TokenValidated(TokenValidatedContext context)
{
var claims = new List<Claim>();
var claim = new Claim(ClaimTypes.Role, "Test", ClaimValueTypes.String, "Issuername")
context.Principal.AddIdentity(new ClaimsIdentity(claims));
return Task.FromResult(0);
}

然而,这从来都不是那么容易。我想要的声明依赖于对服务的外部调用,地址存储在配置中。

在 ConfigureServices 中,我还添加了各种用于依赖注入(inject)的类,这些类对 Controller 来说工作正常。

services.AddTransient<IRoleClaims, RoleClaims>();

这个 RoleClaims 是我想从 TokenValidated 方法调用的一个类,但据我所知我不能在这里使用 DI。我也无法访问 ServiceCollection 以通过 ActivatorUtilities.CreateInstance 获取它。

RoleClaims 的构造函数如下所示:

public RoleClaims(IOptions<EmployeeConfiguration> configuration)

所以,大问题:这应该如何工作?我能以某种方式在 TokenValidated 方法中使用依赖注入(inject)吗?我是否试图在错误的地方添加自己的声明?

最佳答案

在 ASP.NET Core 2.0 中,您可以使用以下方法从容器中获取服务:

private async Task TokenValidated(TokenValidatedContext context)
{
var widget = ctx.HttpContext.RequestServices.GetRequiredService<Widget>();
...
}

关于c# - 如何在使用依赖注入(inject)的 ASP.NET Core 2 中使用 OIDC 登录到 Azure AD 后添加自己的声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com