1

Situation

I have a keycloak server (v12.0.2) running with a client that has some roles. I can add custom attributes to that roles and retrieve them. No problem. But the roles always return an array.

entering key "foo" and value "bar" gives me

 "attributes": {
    "foo": [
      "bar"
    ]
  }

What I would like to have

I would like to have multiple entries in the array. To stay in the previous example, I would like to have "bar" and "baz".

 "attributes": {
    "foo": [
      "bar",
      "baz"
    ]
  }

What I have tried

  • Simply adding 2 entries with the same key - that just leads to overwriting the first entry with the second. So I get
 "attributes": {
    "foo": [
      "baz"
    ]
  }
  • Supplying an array index in the key ("foo[0]" = "bar" and "foo[1]" = "baz" is just two different keys and giving me
  "attributes": {
    "foo[0]": [
      "bar"
    ],
    "foo[1]": [
      "baz"
    ]
  }
  • Separating the values with semicolon, space or comma returns
  "attributes": {
    "foo": [
      "bar,baz"
    ]
  }

(and the same with ";" or " " respectively)

Is there any way to do that or do I have to go with custom defined separators and split the string in my application (which is not a problem, but I think getting the values as an array would be better)

MCMLXXXII
  • 75
  • 6

2 Answers2

1

You can use ## as a delimiter, example: bar##baz . But with this delimiter the order of the array is not guaranteed , though you save the data as bar##baz the array may return as foo[0]= "baz" and foo[1] as="bar".

If the order is not important you can try this delimiter.

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
vpk
  • 26
  • 4
  • Thank you very much! The order does indeed not matter for me. May I ask if you found that in the documentation and I was just too blind to see it? – MCMLXXXII Dec 07 '21 at 08:49
  • @MCMLXXXII , It's not part of the documentation, You can refer this thread https://stackoverflow.com/questions/60767085/keycloak-map-multiple-user-attributes/64008332#64008332 – vpk Dec 09 '21 at 15:00
0

I have faced the similar issue and tried with different steps

  1. Protocol mapper multivalued is True and the attribute value "foo"##"bar", this works and output as ["foo", "bar"]
  2. both foo##bar and "foo##bar" didn't work for me and produces error in admin console evaluate user

Now to use option 1 with Rest API payload is not possible because it comes with invalid json, so make it work using a workaround, Turn off multivalued option in protocol mapper

Rest API Payload for the same looks like

{
  "attributes": {
    "somekey": "[\"foo\", \"bar\"]"
  }
}

Only issue will comes when you retrieve the user info it will look like this

"somekey": [
    "[\"foo\", \"bar\"]"
]

with javascript you can parse the array and do operation

if someone find other useful solution please share

Yash
  • 141
  • 1
  • 12