Add custom claims to access token in IdentityServer4
All identity providers are flexible and allow you to add custom claims in the issued access token. IdentityServer4 is no different in this scenario. Here is a short manual how to add custom claims in IdentityServer4 access token response.
You need to implement a ProfileService:
public class ProfileService : IProfileService
{
public ProfileService(
UserManager<PafUser> userManager)
{
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var user = await _userManager.GetUserAsync(context.Subject);
var claims = new List<Claim>
{
new Claim("custom_claim1", user.CustomClaim1),
new Claim("custom_claim2", user.CustomClaim2),
};
context.IssuedClaims.AddRange(claims);
}
public async Task IsActiveAsync(IsActiveContext context)
{
var user = await _userManager.GetUserAsync(context.Subject);
context.IsActive = (user != null) && user.IsActive;
}
private readonly UserManager<PafUser> _userManager;
}
Then you need to register it in the Startup.cs
services.AddIdentityServer()
.AddProfileService<ProfileService>();
You need to make sure the claims are in the scopes your client is requesting
"IdentityServer": {
"IdentityResources": [
{
"Name": "openid",
"DisplayName": "openid",
"Required": true,
"UserClaims": [
"sub",
"custom_claim1",
"custom_claim2"
]
}
]
...
}