asp.net 身份:身份验证后,将自定义用户声明添加到 AAD 提供的令牌中
根据我的理解,您的 MVC 应用程序配置为使用 ASP.NET Identity 进行用户身份验证,并且您还使用
Microsoft.Owin.Security.ActiveDirectory 包来支持 AAD JWT 不记名令牌身份验证,如下所示:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = "{AAD-client-ID}"
},
Tenant = "{tenantID}"
});
此时,上述中间件将解码令牌并创建一个ClaimsIdentity 用于包装来自传入 JWT 令牌的声明。根据我的理解,您无法修改控制器下的传入令牌,但您可以在中间件设置下处理此问题,如下所示:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = "{AAD-client-ID}"
},
Tenant = "{tenantID}",
Provider = new OAuthBearerAuthenticationProvider()
{
OnValidateIdentity = (context) =>
{
//check context.Ticket.Identity.Name
//add your additional claims here
context.Ticket.Identity.AddClaim(new Claim("test02", "test02"));
return Task.FromResult(0);
}
}
});
此外,我将使用Microsoft.Owin.Security.OpenIdConnect 中间件来使用 OpenIdConnect 进行 AAD 身份验证,如下所示:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
SecurityTokenValidated = async (x) =>
{
var identity = x.AuthenticationTicket.Identity;
//check the name, add additional claims
identity.AddClaim(new Claim("test", "test"));
await Task.FromResult(0);
}
}
});
或者您可以尝试在控制器中添加声明,如下所示:
var identity= User.Identity as ClaimsIdentity;
identity.AddClaim(new Claim("test1", "test1"));
HttpContext.GetOwinContext().Authentication.SignIn(identity);
详情,您可以关注Integrate Azure AD into a web application using OpenID Connect。