Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the user roles with the keycloak userinfo endpoint

How can I get the the roles included in the reply of the userinfo endpoint in keycloak. I defined a "Role Mapping" for the user in keycloak. When I call the userinfo endpoint I get the fields like email name etc, but the roles are not included in the reply. When I call the auth endpoint I get the access_token and in the field scope has roles included. Here is the reply from the auth endpoint:

access_token" QJsonValue(string, "eyJhb...")
"expires_in" QJsonValue(double, 300)
"not-before-policy" QJsonValue(double, 0)
"refresh_expires_in" QJsonValue(double, 1800)
"refresh_token" QJsonValue(string, "eyJhb...")
"scope" QJsonValue(string, "profile email roles")
"session_state" QJsonValue(string, "20b48536-4b38-4aa6-9072-e8309833402e")
"token_type" QJsonValue(string, "bearer")

I also tried to call the userinfo endpoint with the attribute "scope=roles", but this didn't work.

like image 849
Bumblebee Avatar asked Sep 18 '19 16:09

Bumblebee


People also ask

What is the UserInfo endpoint?

The UserInfo endpoint is an OAuth 2.0 protected resource of the Connect2id server where client applications can retrieve consented claims, or assertions, about the logged in end-user. The claims are typically packaged in a JSON object where the sub member denotes the subject (end-user) identifier.


3 Answers

As someone already mentioned, it's a bug. I heard it's fixed in latest version of keycloak.

I eventually fixed with this setting without upgrading to the fixed version of keycloak.

When you add User Realm Role, it will have "realm_access.roles" as Token Claim Name. You need to change it to "roles". Then it will show correctly within userinfo.

enter image description here

like image 68
handicop Avatar answered Oct 24 '22 18:10

handicop


For those whose above answer didn't work, I have spent the whole day figuring it out.
Basically, you have to go to client Scopes--> roles --> then move to Mappers tab, select client roles Add to Id token, access token and userinfo on

Here is the Screenshot Client Roles

like image 35
Kancer Avatar answered Oct 24 '22 20:10

Kancer


Should be this issue: https://keycloak.discourse.group/t/resource-access-claim-missing-from-userinfo-until-i-change-the-name/1238

When renaming the claim in Client Scopes -> roles -> Mappers -> realm roles/client roles, i.e. realm_access.roles to realm_accessy.roles (and setting Add to userinfo to ON), it is included in userinfo :-/

like image 33
Torsten Römer Avatar answered Oct 24 '22 19:10

Torsten Römer