How to add custom claims to access token in IdentityServer4?
Solution 1
You should implement your own ProfileService
.
Have a look in this post which I followed when I implemented the same:
Here is an example of my own implementation:
public class ProfileService : IProfileService
{
protected UserManager<ApplicationUser> _userManager;
public ProfileService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
//>Processing
var user = await _userManager.GetUserAsync(context.Subject);
var claims = new List<Claim>
{
new Claim("FullName", user.FullName),
};
context.IssuedClaims.AddRange(claims);
}
public async Task IsActiveAsync(IsActiveContext context)
{
//>Processing
var user = await _userManager.GetUserAsync(context.Subject);
context.IsActive = (user != null) && user.IsActive;
}
}
Don't forget to configure the service in your Startup.cs (via this answer)
services.AddIdentityServer()
.AddProfileService<ProfileService>();
Solution 2
Ok the issue here is this:
although you have configured your available Identity resources correctly (both standard & custom), you also need to explicitly define which ones are a necessity when calling your api resource. In order to define this you must go to your Config.cs
class on ExampleIdentityServer
project and provide a third argument like on the new ApiResouirce
constructor. Only those will be included into the access_token
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API", new[] { JwtClaimTypes.Subject, JwtClaimTypes.Email, JwtClaimTypes.Phone, etc... })
};
}
In essence this means that I got my identity claims configured for my organization but there may be more than one APIs involved and not all of the APIs make use of all available profile claims. This also means that these will be present inside your ClaimsPrincipal
all the rest can still be accessed through the "userinfo" endpoint as a normal http call.
NOTE: regarding refresh tokens:
If you chose to enable refresh tokens via AllowOfflineAccess = true
, you may experience the same behavior upon refreshing the access_token "GetProfileDataAsync does not executed!". So the claims inside the access_token stay the same although you get a new access_token with updated lifetime. If that is the case you can force them to always refresh from the Profile service by setting UpdateAccessTokenClaimsOnRefresh=true
on the client configuration.
Solution 3
Issue found.
In startup.cs, instead of adding services.AddTransient<IProfileService, ProfileService>();
, add .AddProfileService<ProfileService>()
to services.AddIdentityServer()
.
You will end up with
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<ProfileService>();
Thanks for Coemgen for helping out! Nothing wrong with the code, just the startup was wrong.
Solution 4
You can include any claim by using UserClaims option in your GetIdentityResources() in the config class :
UserClaims: List of associated user claim types that should be included in the identity token. (As per the official documentation) http://docs.identityserver.io/en/release/reference/identity_resource.html#refidentityresource
001
Only questions with complete answers are accepted as solutions.
Updated on July 05, 2022Comments
-
001 almost 2 years
I am using IdentityServer4.
I want to add other custom claims to access token but I'm unable to do this. I have modified Quickstart5 and added ASP.NET Identity Core and the custom claims via ProfileService as suggested by Coemgen below.
You can download my code here: [zip package][3]. (It is based on: Quickstart5 with ASP.NET Identity Core and added claims via ProfileService).
Issue: GetProfileDataAsync does not executed.
-
001 almost 7 yearsI tried that, it doesnt work!
-
001 almost 7 yearsI followed this, it does not work! docs.identityserver.io/en/release/topics/…
-
001 almost 7 yearsthanks for that, however, it still does not work! no claims are added!
-
Blennouill almost 7 yearsAre you target the GetProfileDataAsync function in debug mode ?
-
001 almost 7 yearsI am viewing the claims on the "secure" page here github.com/IdentityServer/IdentityServer4.Samples/blob/release/…
-
Blennouill almost 7 yearsWhat happens when you target your API ? What are the claims ?
-
001 almost 7 yearsAll claims passed on the secure page is the same claims passed by the api. And they do not include the claims i added above via "ProfileService"
-
Blennouill almost 7 yearsOkay, but if you add a break point, did you target GetProfileDataAsync ?
-
Blennouill almost 7 yearsLet us continue this discussion in chat.
-
001 almost 7 yearsOn startup, it executes this " services.AddTransient<IProfileService, ProfileService>(); //AddClaims" but it break point, does not execute GetProfileDataAsync method
-
001 almost 7 yearsLet us continue this discussion in chat.
-
Blennouill almost 7 yearsThat's interresting. You also should be able to use services.AddTransient<IProfileService, ProfileService>(); .
-
AdrienTorris almost 7 yearsThere is a great example on the Microsoft Architecture GitHub repository : github.com/dotnet-architecture/eShopOnContainers/blob/master/…
-
001 almost 7 years@Coemgen you can do that too! but you must add " services.AddTransient<IProfileService, ProfileService>();" after "services.AddIdentityServer()" :)
-
Rob L over 6 yearsYou can simply do this services.AddTransient<IdentityServer4.Services.IProfileService, CustomUserProfileService>(); and that will work
-
pushist1y about 6 yearsI believe that if you want to stick with
services.AddTransient<IProfileService, ProfileService>();
you should do that after adding identityserver to services so your registration will override that one made by IS -
infografnet about 4 yearsIf that does not work you may try to delete cookies for that site or at least to log out from your application and IdentityServer
-
NET Experts almost 4 yearsThis works perfectly! Thank you.
-
ssougnez over 3 yearsSee the answer of 001 below to have something that works ;-)
-
Bluebaron almost 3 yearsI had a problem where it wasn't being added to the ServicesCollection. I had to move the services.AddTransient above the AddIdentityServer.
-
Sadiq Khoja over 2 yearsif you are calling _userManager.GetUserAsync in Login method to raise UserLoginSuccessEvent then _userManager.GetUserAsync will called twice? hitting DB twice?
-
Stamos about 2 yearsThis doesn't work for client_credentials
-
kennydust almost 2 yearsfor anyone reading, order matters and the profileService should be registered last.