Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

authentication - Keycloak retrieve custom attributes to KeycloakPrincipal

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

KeycloakPrincipal kcPrincipal = (KeycloakPrincipal) servletRequest.getUserPrincipal();

statement.

Keycloak principal does'nt cotain all the information i need about the authenticated user. Is it possibile to customize my own principal type? On the keycloak-server-end i ve developed a user federation provider. I saw that UserModel makes possible to add a set of custom attributes to my user.

Is it possibile to insert my custom principal in that code?

Is it possible to retrieve this attributes from keycloak principal?

What is the way?

question from:https://stackoverflow.com/questions/32678883/keycloak-retrieve-custom-attributes-to-keycloakprincipal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...