To add custom attributes you need to do three things:
- Add attributes to admin console
- Add claim mapping
- 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:
- Open the admin console of your realm.
- Go to Clients and open your client
- This only works for Settings > Access Type confidential or public (not bearer-only)
- Go to Mappers
- Create a mapping from your attribute to json
- Check "Add to ID token"
Access claims:
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…