0

I would like Keycloak (1.4.0) to include the users' chosen locale to the ID token.

I have come as far as creating a user attribute mapper, which was supposed to map the locale attribute to the token, but it does not work.

Does anybody know how to do this?

Thanks in advance.

Edit: I have learnt what I know abput Keycloak Locales from this class: http://grepcode.com/file/repository.jboss.org/nexus/content/repositories/releases/org.keycloak/keycloak-forms-common-freemarker/1.2.0.Final/org/keycloak/freemarker/LocaleHelper.java#LocaleHelper.0LOGGER

Luka
  • 435
  • 1
  • 7
  • 18

2 Answers2

4

I have managed to solve the problem on my own. I ended up using loadUserProfile() function from Keycloak JS adapter. It loads all the user attributes (including locale) into keycloak.profile object, so I didn't have to configure any mappers.

Luka
  • 435
  • 1
  • 7
  • 18
  • 1
    Good that it's working now. I used custom attributes, apparently profile attributes are handled differently :) – lisa p. Oct 08 '15 at 13:10
  • probably it makes internally a call to userinfo profile. With id_token you can skip the additional call. Still better to use what is simpler for you – Sergey Ponomarev Feb 01 '22 at 21:28
3

I suppose you already have something like this:

  1. Open the admin console of your realm.
  2. Go to Clients and select your client
  3. This only works for Settings > Access Type confidential or public (not bearer-only)
  4. Go to Mappers
  5. Create a mapping from your attribute to json
  6. Check "Add to ID token"

To access the mapped claim you use something like this:

final Principal userPrincipal = httpRequest.getUserPrincipal();

if (userPrincipal instanceof KeycloakPrincipal) {

    KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) userPrincipal;
    IDToken token = kp.getKeycloakSecurityContext().getIdToken();

    Map<String, Object> otherClaims = token.getOtherClaims();

    if (otherClaims.containsKey("YOUR_CLAIM_KEY")) {
        yourClaim = String.valueOf(otherClaims.get("YOUR_CLAIM_KEY"));
    }
} else {
    throw new RuntimeException(...);
}

Hope this helps and fits your use case. I used this for a custom attribute I added with a custom theme.

lisa p.
  • 2,138
  • 21
  • 36
  • I already tried this, but the problem is that locale is not accesible in that way, so i had to work with user profile. – Luka Oct 05 '15 at 18:09
  • I did like you suggested, but I only get a null IDToken. Adding the data to the access token works, though, I can then get it from there. This is with spring-security 4.0 and keycloak 1.7 – mkm13 Jan 14 '16 at 12:02
  • That's strange. Even without custom variables you should get the standard IdToken and not null. – lisa p. Jan 15 '16 at 08:39