Include user locale to the Keycloak ID token

后端 未结 2 759
星月不相逢
星月不相逢 2021-01-27 11:57

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-27 12:21

    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 kp = (KeycloakPrincipal) userPrincipal;
        IDToken token = kp.getKeycloakSecurityContext().getIdToken();
    
        Map 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.

提交回复
热议问题