Keycloak retrieve custom attributes to KeycloakPrincipal

前端 未结 2 1652
北海茫月
北海茫月 2020-11-28 21:31

In my rest service i can obtain the principal information after authentication using

KeycloakPrincipal kcPrincipal = (KeycloakPrincipal) servletRequest.getU         


        
2条回答
  •  盖世英雄少女心
    2020-11-28 22:06

    To add custom attributes you need to do three things:

    1. Add attributes to admin console
    2. Add claim mapping
    3. Access claims

    The first one is explained pretty good here: https://www.keycloak.org/docs/latest/server_admin/index.html#user-attributes

    Add claim mapping:

    1. Open the admin console of your realm.
    2. Go to Clients and open 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"

    Access claims:

    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.

提交回复
热议问题