I would assume this to be straight forward but I can't find it in the docs.
The following curl command:
curl \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
'https://$URL/auth/realms/$REALM/protocol/openid-connect/userinfo'
results in:
{
"sub": "8182...415",
"email_verified": true,
"name": "n.a. n.a.",
"groups": [],
"preferred_username": "foo@example.com",
"given_name": "n.a.",
"family_name": "n.a.",
"email": "foo@example.com"
}
How do I get the custom attributes for a user?
You can get the user attributes with the get users endpoint from Admin Rest API:
GET /{realm}/users
with the query parameters, exact=true
and username
.
Step-by-Step:
You can get that information using the Keycloak Admin REST API; to call that API, you need an access token from a user with the proper permissions. For now, I will be using the admin
user from the master
realm:
curl https://${KEYCLOAK_HOST}/auth/realms/master/protocol/openid-connect/token \
-d "client_id=admin-cli" \
-d "username=$ADMIN_NAME" \
-d "password=$ADMIN_PASSWORD" \
-d "grant_type=password"
You will get a JSON response with the admin's token. Extract the value of property access_token
from that response. Let us save it in the variable $ACCESS_TOKEN
for later reference.
To get the user attributes from your realm $REALM_NAME
:
curl -X GET https://${KEYCLOAK_HOST}/auth/admin/realms/${REALM_NAME}/users/?username=${USERNAME}&exact=true \
-H "Content-Type: application/json" \
-H "Authorization: bearer $ACCESS_TOKEN"
From the response extract the user attributes
for example as follows:
jq -r .[].attributes
To retrieve custom user attributes via the userinfo
endpoint you need to create a protocol Mapper for the client used to authenticate the user.
That mapper can also be created with the Keycloak Admin rest API. For a more detailed answer on how to create Protocol Mappers for user-attributes (including for the old and new Keycloak APIs) please have a look at the this SO answer.
Or you can do it via Keycloak Admin UI as follows, in the Keycloak go to:
realm
clients
client
for your use-case(For the OLD Keycloak UI)
Mappers
Create
Mapper Type
as User Attribute
User Attribute
with your custom user attributeuserinfo
endpointSave
(For the NEW Keycloak UI)
Client Scopes
Configure a new mapper
(or Add Mapper
> By configuration
if you have already created mappers before for this client)User Attribute
User Attribute
with your custom user attributeuserinfo
endpointSave
This is enough to enabled your custom user attribute
to be retrieved from the userinfo
endpoint