How to dynamically loaded claims for a client, not user, IdentityServer?

358 Views Asked by At

I am wondering if/how I can dynamically loaded claims for a client (instead of a user) under IdentityServer4. For my MVC client apps, I can use IdentityServer4's IProfileService API to dynamically load claims for a user, and that works great. But I need to do the same to my server-to-server client app (client credential grant type) which IProfileService API functions doesn't seem to cover. Can this be done? If so, now?

2

There are 2 best solutions below

0
Alexu On BEST ANSWER

I have solved this problem by implementing

public class MyClaimService : DefaultClaimsService

By overriding the GetAccessTokenClaimsAsync function of this class, I can add my custom claims into the token. And unlike IProfileService, which only apply to identitys, this function apply to clients (apps) as well.

7
AngelBlueSky On

Maybe you can try this way:

whit Clients loaded from code:

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "Application1",
                ClientName = "Application1",
                ....
                AllowedScopes = { "application1.api.full_access"}
                AccessTokenLifetime = 1800,
                IdentityTokenLifetime = 1800,
                Claims = new Claim[]
                {
                    new Claim("Role", "admin"),
                    new Claim(JwtClaimTypes.Name, "JwtClaimTypes.Name"),
                    new Claim(JwtClaimTypes.Role, "JwtClaimTypes.Role")
                }
            
            }....
    }

with Clients loaded via appsettings.json:
"Clients": [
  {
    "ClientId": "Application1",
    "ClientName": "Application1",
    "Enabled": true,
    "Claims": [
      {
        "Type": "role",
        "Value": "admin"
      },
      {
        "Type": "name",
        "Value": "myapp"
      }
    ],
    ....
  }
]