如何覆盖openid连接声明



我有一个ASP。. NET MVC框架web应用程序。我想使用。net身份和OpenId连接身份验证(微软帐户)。

它工作并重定向到我想要的另一个控制器。在这个目标控制器中,我从声明(从Azure AD返回)中获取信息。

我想要的是从Azure向这个集合添加更多的声明,或者根据我的需要创建一组新的声明。我设置索赔如下,但当调试器击中另一个控制器时,我只看到Azure AD返回的默认索赔;我的修改没有反映在索赔收集中。

我如何添加声明,这是可用的OpenId连接(微软)和。net身份验证?

这是我在控制器中设置示例声明的方式:

var identity = new ClaimsIdentity("ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.AddClaim(new Claim("test", "test"));
IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut("ApplicationCookie");
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity); 

这是我在Startup中的配置:

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Sets the ClientId, authority, RedirectUri as obtained from web.config
ClientId = clientId,
Authority = authority,
// PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
PostLogoutRedirectUri = redirectUri,
Scope = OpenIdConnectScope.OpenIdProfile,
// ResponseType is set to request the code id_token - which contains basic information about the signed-in user
ResponseType = OpenIdConnectResponseType.CodeIdToken,
AuthenticationMode = AuthenticationMode.Passive,
// OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed
},
TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
RoleClaimType = System.Security.Claims.ClaimTypes.Role,
ValidateIssuer = false
}
});

您有两个选择。钩子到AddCookie提供的各种事件和AddOpenIDConnect. 或者添加自定义声明转换,如:

public class BonusLevelClaimTransformation : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (!principal.HasClaim(c => c.Type == "bonuslevel"))
{
//Lookup bonus level.....
principal.Identities.First().AddClaim(new Claim("bonuslevel", "12345"));
}
return Task.FromResult(principal);
}
}

你还需要在Startup.cs中注册它像

services.AddTransient<IClaimsTransformation, BonusLevelClaimTransformation>();

为了补充这个答案,我写了一篇博客文章,详细介绍了这个问题本主题是:调试ASP中OpenID连接声明问题。网络核心

最新更新