Get user roles from Keycloak in Spring/Jhipster

I faced a problem when I tried to use user roles on JHipster 5.x to limit access or filter results; Keycloak returns a token that includes user roles but under wrong path! Keycloak put user roles at realm_access.roles while Spring Security check roles at root of token playload.

I solve this issue in Keycloak and add user roles in roles of playload; Here I want share it with you.

Select your realm in Keycloak and from the menu select Client Scopes:

Keycloak Master Realm

Select Roles:

Keycloak Client Scopes

Note: If there isn't any roles, so create it with this detail(they are optional):

Keycloak Roles Client Scope

Then go to Mappers tab and Create new mapper:

Keycloak Mappers of Roles Client Scope

fill form like this and save it:

Keycloak new Mapper

Note: If you created roles manually, you should add it to your client manually too; Go to Clients, Select your client (eg Mobile), go to Client Scopes tab, and add roles (or any name that you choosed) to Assigned Default Client Scopes.

Keycloak Assign Scope

Now check your token and check roles has been added:

Token Decoded

No comments: