向 AAD OpenIDConnect 身份验证用户添加自定义声明

Adding Custom Claim to AAD OpenIDConnect Authenticated User

我有一个 MVC 应用程序,.NET v. 4.5.2,我需要在其中向 AAD OpenIDConnect 身份验证用户添加自定义声明。

验证码(Startup.cs):

    string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
    string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];
    static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
    string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

    public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
            ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUrl,

            PostLogoutRedirectUri = redirectUrl,

            Scope = OpenIdConnectScope.OpenIdProfile,

            ResponseType = OpenIdConnectResponseType.IdToken,

            TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true
                },

            Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed,
                    AuthorizationCodeReceived = async context =>
                    {
                        var id = new ClaimsIdentity(context.AuthenticationTicket.Identity.AuthenticationType);
                        //var id = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType);

                        id.AddClaims(context.AuthenticationTicket.Identity.Claims);
                        var appToken = context.ProtocolMessage.AccessToken;
                        id.AddClaim(new Claim("MyTestClaim", appToken));
                        id.AddClaim(new Claim("MyTestClaim2", "TestValue"));

                        context.AuthenticationTicket = new AuthenticationTicket
                        (
                             new ClaimsIdentity(id.Claims, context.AuthenticationTicket.Identity.AuthenticationType),
                               context.AuthenticationTicket.Properties
                        );
                    }
               }
            }
        );

家庭控制器中的以下行始终为空:

var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
var test = userClaims?.FindFirst("MyTestClaim")?.Value;

显示了所有来自正在验证的用户的声明,但我无法显示 "MyTestClaim"。

原来我的代码在错误的 OpenIdConnectAuthenticationNotifications 部分。我应该使用 SecurityTokenValidation,而不是使用 AuthorizationCodeReceived。在此处添加自定义声明还(到目前为止)确保了当用户导航到应用中的不同页面时自定义声明不会消失。

 Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed,
                    SecurityTokenValidated = async (x) =>
                    {
                        var identity = x.AuthenticationTicket.Identity;
                        identity.AddClaim(new Claim("test", "test"));

                        await Task.FromResult(0);
                    }
                 }

Credit