How to add custom claims to access token in IdentityServer4?

68,348

Solution 1

You should implement your own ProfileService. Have a look in this post which I followed when I implemented the same:

https://damienbod.com/2016/11/18/extending-identity-in-identityserver4-to-manage-users-in-asp-net-core/

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

Share:
68,348
001
Author by

001

Only questions with complete answers are accepted as solutions.

Updated on July 05, 2022

Comments

  • 001
    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
    001 almost 7 years
    I tried that, it doesnt work!
  • 001
    001 almost 7 years
    I followed this, it does not work! docs.identityserver.io/en/release/topics/…
  • 001
    001 almost 7 years
    thanks for that, however, it still does not work! no claims are added!
  • Blennouill
    Blennouill almost 7 years
    Are you target the GetProfileDataAsync function in debug mode ?
  • 001
    001 almost 7 years
    I am viewing the claims on the "secure" page here github.com/IdentityServer/IdentityServer4.Samples/blob/relea‌​se/…
  • Blennouill
    Blennouill almost 7 years
    What happens when you target your API ? What are the claims ?
  • 001
    001 almost 7 years
    All 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
    Blennouill almost 7 years
    Okay, but if you add a break point, did you target GetProfileDataAsync ?
  • Blennouill
    Blennouill almost 7 years
  • 001
    001 almost 7 years
    On startup, it executes this " services.AddTransient<IProfileService, ProfileService>(); //AddClaims" but it break point, does not execute GetProfileDataAsync method
  • 001
    001 almost 7 years
  • Blennouill
    Blennouill almost 7 years
    That's interresting. You also should be able to use services.AddTransient<IProfileService, ProfileService>(); .
  • AdrienTorris
    AdrienTorris almost 7 years
    There is a great example on the Microsoft Architecture GitHub repository : github.com/dotnet-architecture/eShopOnContainers/blob/master‌​/…
  • 001
    001 almost 7 years
    @Coemgen you can do that too! but you must add " services.AddTransient<IProfileService, ProfileService>();" after "services.AddIdentityServer()" :)
  • Rob L
    Rob L over 6 years
    You can simply do this services.AddTransient<IdentityServer4.Services.IProfileServi‌​ce, CustomUserProfileService>(); and that will work
  • pushist1y
    pushist1y about 6 years
    I 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
    infografnet about 4 years
    If 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
    NET Experts almost 4 years
    This works perfectly! Thank you.
  • ssougnez
    ssougnez over 3 years
    See the answer of 001 below to have something that works ;-)
  • Bluebaron
    Bluebaron almost 3 years
    I had a problem where it wasn't being added to the ServicesCollection. I had to move the services.AddTransient above the AddIdentityServer.
  • Sadiq Khoja
    Sadiq Khoja over 2 years
    if you are calling _userManager.GetUserAsync in Login method to raise UserLoginSuccessEvent then _userManager.GetUserAsync will called twice? hitting DB twice?
  • Stamos
    Stamos about 2 years
    This doesn't work for client_credentials
  • kennydust
    kennydust almost 2 years
    for anyone reading, order matters and the profileService should be registered last.