Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak map multiple user attributes

Tags:

keycloak

I've followed the guide at [1] to map a single user attribute. However, I need to map all attributes to an array, so that every attribute for a particular User shows up in an attribute array of the access token (Or better, restrict attributes to a certain group of attributes, but I guess user attributes are only a flat key/value map).

I tried out setting a wildcard * in the User Attribute field of the client mapper. But no matter what I do, I can ony set one attribute at a time given an actual attribute key of a user's attribute map.

[1] Keycloak retrieve custom attributes to KeycloakPrincipal

like image 365
benjist Avatar asked Aug 25 '26 14:08

benjist


2 Answers

I was in trouble with the same problem.

I have tried the following:

  1. Added a key "department" with a single value for example "finance". Adding a second key "department" with another value "development" overwrites the initial entry.
  2. I also have tried to put something like a list into the value column, such as "development, finance" or "development; finance" but this is treated as a single value too.

If you use "development##finance" in admin console, the user will have "department" attribute with 2 values "development" and "finance".

The "##" seem to be the delimiter to use.

So, if you mark "multivalued" switch in your protocolMapper for "department" attribute, the accessToken will contain list with 2 values "development" and "finance".

"department": [ "development", "finance" ]

This worked for me.

KeyCloak version 11.0.2

like image 112
Fabio Avatar answered Aug 27 '26 05:08

Fabio


Actually there is an easier solution (I successfully tested it with Keycloak version >= 21 - but might also work for previous versions).

You can just simply add multiple attributes with the same key:

User Attributes

A multivalued client scope mapper (See Woodys answer) will then combine all of the values into a single array within the token:

Token

Please note: When you are using the Admin API to update user attributes you have to send the attribute as an array in order not to override any existing values:

{
   "attributes":{
      "data-disclosure":[
         "{\"version\":1,\"grantedAt\":\"2023-07-21T13:47:41.357Z\"}",
         "{\"version\":2,\"grantedAt\":\"2023-07-21T13:47:41.357Z\"}"
      ]
   }
}
like image 38
Bennet Hölscher Avatar answered Aug 27 '26 05:08

Bennet Hölscher