How do I get the roles and attributes of a user using the Java Client of Keycloak? Below is the code that I have written to get the access token of a user, however, I am not able to find the way to get the roles assigned to that user.
Configuration configuration = new Configuration();
configuration.setRealm("foo");
configuration.setResource("foo");
configuration.setBearerOnly(Boolean.TRUE);
configuration.setAuthServerUrl("http://localhost:8080");
configuration.setCredentials(Map.of("secret", "FV3P4ajYHedAUDtOa55EX5nzK8zc6jUA"));
AuthzClient authzClient = AuthzClient.create(configuration);
AuthorizationRequest request = new AuthorizationRequest();
AuthorizationResponse authorize = authzClient.authorization("john.doe", "john.doe").authorize(request);
String token = authorize.getToken();
log.info("Auth bearer token is {}", token);
You have the token as a String, namely:
String token = authorize.getToken();
now you just need to parse it to get the Realm and Client roles, which are encoded in the token. For that you can use the class TokenVerifier from org.keycloak.TokenVerifier.
For example:
try {
AccessToken token = TokenVerifier.create(tokenString, AccessToken.class).getToken();
System.out.printf("Realm 'foo' = Roles %s%n", token.getRealmAccess().getRoles());
token.getResourceAccess().forEach((k, v) -> System.out.printf("Client '%s' = Roles '%s'%n", k, v.getRoles()));
} catch (VerificationException e) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With