How to add Custom Claims from User Attributes in Keycloak

Overview

Recently, as I work on integrating Keycloak to DAML ledger, I need to associate users on Keycloak with parties on the DAML ledger.

If you are working on DAML, you probably know to access the DAML ledger API, you need to use access token too. There are two fields needed in the JWT token: actAs and readAs. If you don’t know what DAML is, don’t worry, you don’t need to know it :D.

In this post, I’m going to show you how you can add custom claims from user attributes in Keycloak.

Adding attributes to user

The first thing you need to do is to create an user on Keycloak (if you haven’t) and add your desired attributes to that user:

Adding attributes to user
Adding attributes to user

As you can see, in the screenshot, I added two attributes namely actAs, readAs. The name of these attributes doesn’t matter as they don’t display on the token.

Next, you will need to add mappers to the account-cli client.

Add mappers to account-console client

First, click on Clients and select account-console on the client list:

select account-console client
select account-console client

Next, click on the Mappers tab and then on the Create button:

create a mapper
create a mapper

Then, you can configure the mapper as follow:

configure a mapper
configure a mapper

There are something in this screen you need to pay attention to:

  1. The Mapper Type must be User Attribute as you want to extract the value from the attribute you set previously
  2. Token claim name is the actual text that is displayed in the JWT token
  3. Claim json type: Depends on your application, however, in this case, it’s a string
  4. The toggle buttons are almost self-explanatory. The one I marked with number 2 is important. If you turn Multivalued option on, the value will be displayed inside a JSON array ([value])

Repeat the process with other attributes you want to add to the access token.

View the attributes in the access token

Let’s back to the user and impersonate her to get a token:

impersonate user on keycloak
impersonate user on keycloak

On the next screen, open the developer console on your browser and copy the token:

Copy token in Chrome console
Copy token in Chrome console

Now, if you paste that token in jwt.io debugger, you will see the new values added there:

new claims added to Keycloak's JWT access token
new claims added to Keycloak’s JWT access token

Conclusion

In this post, I’ve shown you how to add claims to Keycloak’s access token from user’s attributes. You can mark the value as multiplevalued to wrap it in a JSON array (depends on your use case). This post shows just one simple use case. From the available options, you can configure to make the claim much more flexible.


Leave a Reply

Your email address will not be published. Required fields are marked *