Search code examples
c#oauthtokenopenid-connectaccess-token

Keycloak set custom in access_token claim via API


I need to set a custom claim in the access_token from within a C# application. Is there a way to achive this? So that I can create custom access_tokens on the fly. I read though the Keycloak API reference but wan not able to find a solution. I need this because I have a User that, depending on the application state, should get access to different ressources. I dont want to create different user to achive this. I do not want to save information into the cookies to achive this. And I also do not want to save information in URL to achive this.

I already tried to use a uma-ticket token for this as described here. But all i got was this error:

{
    "error": "invalid_grant",
    "error_description": "Invalid bearer token"
}

Solution

  • The most common option is to implement dynamic behaviour via claims. At the time of token issuance, the authorization server can reach out to an API endpoint (or database), to send account attributes and receive back custom attributes.

    In Keycloak you need to use a protocol mapper for this. The last time I looked you had to develop one in Java, then configure it in the Admin UI for your client app. There is a worked example here.

    This is usually a better design than trying to issue new user level access tokens on the fly. Eg an access token contains the important values used for authorization, such as role=manager or subscription_level=gold, so that the claims are trusted. The resources they grant access to could then vary a little based on runtime conditions.