asp.net identity: after authentication, add custom user claims to a token provided by AAD

时光怂恿深爱的人放手 提交于 2019-12-08 06:30:22

asp.net identity: after authentication, add custom user claims to a token provided by AAD

Based on my understanding, your MVC application is configured to use ASP.NET Identity for user authentication and you also use the Microsoft.Owin.Security.ActiveDirectory package for supporting AAD JWT bearer token authentication as follows:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        TokenValidationParameters = new TokenValidationParameters()
        {
            ValidAudience = "{AAD-client-ID}"
        },
        Tenant = "{tenantID}"
    });

At this point, the above middle-ware would decode the token and create a ClaimsIdentity for wrapping the claims from the incoming JWT token. Per my understanding, you could not modify the incoming token under your controller, but you could handle this under the middle-ware settings as follows:

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);
            }
        }
    });

Moreover, I would use Microsoft.Owin.Security.OpenIdConnect middleware to use OpenIdConnect for AAD authentication as follows:

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);
            }
        }
    });

Or you could try to add the claims in your controller as follows:

var identity= User.Identity as ClaimsIdentity;
identity.AddClaim(new Claim("test1", "test1"));
HttpContext.GetOwinContext().Authentication.SignIn(identity);

Details, you could follow Integrate Azure AD into a web application using OpenID Connect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!