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.