How to add custom claims to access token in IdentityServer4? [closed]
Asked Answered
C

4

83

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 execute.

Cigarillo answered 26/6, 2017 at 13:36 Comment(1)
I'm rather perplexed by this question, 001. You're clearly a very experienced user of Stack Overflow, but you've put your code in a file locker rather than in the question, and thus it is - as you must know - off topic. Are you able to repair the question, so it is not put on hold?Elin
I
128

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

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>();
Intercessor answered 28/6, 2017 at 6:58 Comment(17)
thanks for that, however, it still does not work! no claims are added!Cigarillo
Are you target the GetProfileDataAsync function in debug mode ?Intercessor
I am viewing the claims on the "secure" page here github.com/IdentityServer/IdentityServer4.Samples/blob/release/…Cigarillo
What happens when you target your API ? What are the claims ?Intercessor
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"Cigarillo
Okay, but if you add a break point, did you target GetProfileDataAsync ?Intercessor
Let us continue this discussion in chat.Intercessor
On startup, it executes this " services.AddTransient<IProfileService, ProfileService>(); //AddClaims" but it break point, does not execute GetProfileDataAsync methodCigarillo
Let us continue this discussion in chat.Cigarillo
If that does not work you may try to delete cookies for that site or at least to log out from your application and IdentityServerHydrolyse
See the answer of 001 below to have something that works ;-)Tirpitz
I had a problem where it wasn't being added to the ServicesCollection. I had to move the services.AddTransient above the AddIdentityServer.Alvardo
if you are calling _userManager.GetUserAsync in Login method to raise UserLoginSuccessEvent then _userManager.GetUserAsync will called twice? hitting DB twice?Rudolph
This doesn't work for client_credentialsGlance
it is beyond me how information like this dont exist in the acutal documentation. thanks!Emylee
adding claims directly to IssuedClaims is not recommended. the recommended way is to use method context.AddRequestedClaims link to add only requested claims. and define UserClaims in ApiScope link to make those claims represent in requested claims.Acknowledge
I had to add AddProfileService<ProfileService>() after .AddAspNetIdentity<ApplicationUser>() to make it workMamoun
C
58

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 execute!". 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.

Commissar answered 5/7, 2017 at 17:45 Comment(0)
C
47

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.

Cigarillo answered 29/6, 2017 at 10:11 Comment(7)
That's interresting. You also should be able to use services.AddTransient<IProfileService, ProfileService>(); .Intercessor
There is a great example on the Microsoft Architecture GitHub repository : github.com/dotnet-architecture/eShopOnContainers/blob/master/…Ocean
@Coemgen you can do that too! but you must add " services.AddTransient<IProfileService, ProfileService>();" after "services.AddIdentityServer()" :)Cigarillo
You can simply do this services.AddTransient<IdentityServer4.Services.IProfileService, CustomUserProfileService>(); and that will workIronbark
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 ISUranie
This works perfectly! Thank you.Leeann
for anyone reading, order matters and the profileService should be registered last.Arleta
H
1

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

Hodess answered 27/6, 2017 at 18:54 Comment(2)
I tried that, it doesnt work!Cigarillo
I followed this, it does not work! docs.identityserver.io/en/release/topics/…Cigarillo

© 2022 - 2024 — McMap. All rights reserved.