5
votes

what I am trying to do:

  1. I have an app that takes in login credentials: username and password for a user. I have a rest api that internally calls the keycloak REST API: /auth/realms/realmname/protocol/openid-connect/token and gets the access token for this user.

  2. Now I am building another REST API to access a resource where I want to do the following: doSomething(accesstoken, data)

    {

    a) call keycloak API to validate access token and get roles.

    b) if role == manager, process(data)

    c) else: return error msg.

    }

Now, how do I do (a): validating the access token and getting the roles associated with it. I know we can do: auth/realms/realmname/protocol/openid-connect/userinfo but that only gives the details about the user like name, email, etc. but does not display any roles. Here's an example I got:

{
    "name": "test user",
    "sub": "e2bad34d-a1a9-4d70-ac84-bd3a3246023e",
    "email_verified": false,
    "preferred_username": "user",
    "given_name": "test",
    "family_name": "user"
}

As seen, it doesnt give the roles at all. How do I then tell what roles this access token has? Interestingly, when I search for this, many resources are suggesting the above userinfo endpoint. But this merely tells me taht the access token I provided is valid. Does not give roles for that. In other words - it authenticates but does not authorize.

Please suggest.

Thanks, Anand

3
Did you overcome the problem?SoT

3 Answers

8
votes

In Keycloak admin Console, you can configure Mappers under your client. Add a builtin Mapper of type "User Realm Role", then open its configuration e.g. change Token Claim Name if you want.

Client roles can be configured similarly, but they are returned by default in the token under the name resource_access.${client_id}.roles

The the client side you can parse the token to find the roles. E.g. In an angular application and using the keycloak-angular adapter, you can have a the token as a json object by calling keycloak.getKeycloakInstance().tokenParsed.

In a spring boot application and using the Keycloak java api, you can find the roles under the field "otherClaim" in the following class https://www.keycloak.org/docs-api/10.0/javadocs/org/keycloak/representations/AccessTokenResponse.html

In both representations you will find the roles under the "Token Claim Name" defined in the client mapper configuration

2
votes

Additionally, if the full scope is not allowed then you need to add the relevant roles to the scope, so they can appear in the token.

enter image description here

0
votes

After adding role in the roles section , need to move available roles into the Assigned Roles of the scope tab of the respective client section.

[1]: https://i.stack.imgur.com/rPI0V.png