Reputation: 7357
After a webapp is successfully authenticated by Azure Active Directory, I need to add custom claims to the token.
Essentially I want to do this in one of my controllers:
if (ExistsUserInDb(User.Identity.Name))
{
User.Identity.AddClaim("superUser", "true");
}
So that I can keep on reusing the same token when that user does some superPrivilege action on other controllers.
Is this possible?
I've tried these links but they didn't work for me: How to extend available properties of User.Identity How to add claims in ASP.NET Identity
Upvotes: 1
Views: 2278
Reputation: 18465
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.
Upvotes: 2