Hello there,
I wanted to include role attributes in JWT token, which apparently is not possible out of the box: only user attributes can be mapped. I discovered that custom Script Mapper can be the solution.
I managed to configure Keycloak so that I can type in the JavaScript code.
Sadly, the example I found didn’t work. Then I realized that all variables like user
, token
are undefined
.
Here is my sample code of mapper I wrote to debug what’s happening:
/**
* Available variables:
* user - the current user
* realm - the current realm
* token - the current token
* userSession - the current userSession
* keycloakSession - the current keycloakSession
*/
//insert your code here...
var ret = [];
ret.push('Hello');
ret.push(user);
ret.push(realm);
ret.push(token);
ret.push(userSession);
ret.push(keycloakSession);
JSON.stringify(ret);
And the token claim shows something like this (look for x_userid claim):
{
"exp": 1598069388,
"iat": 1598040588,
"jti": "aefbbb2e-adae-4513-b9cd-531c203c4768",
"iss": "http://localhost:9002/auth/realms/hotel",
"aud": "account",
"sub": "9811c27a-f1de-4efa-ab9a-eb53ef29dc4f",
"typ": "Bearer",
"azp": "hotel-ui-react-dev",
"session_state": "5d6d7e9d-52e5-4ef4-a8c7-759f611ee37e",
"acr": "1",
"allowed-origins": [
"http://localhost:3000"
],
"realm_access": {
"roles": [
"hotelier",
"offline_access",
"uma_authorization"
]
},
"resource_access": {
"account": {
"roles": [
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
"scope": "openid profile email",
"email_verified": true,
"x_userid": [
"Hello",
null,
null,
null,
null,
null
],
"preferred_username": "hotel"
}
So definitely the mapper is working, the result appears in JWT token, but since all injected variables are null, code won’t work.
I tried it both via JS client adapter in React app, via Postman and even using obscure “evaluate” function in client settings in admin. Same result everywhere.
I was working on 10.0.2 but started 11.0.1 version (all in Docker) to no avail. Did I miss something?