javaspring-bootpostmankeycloakkeycloak-rest-api

Keycloak PUT-request returns 401 (unauthorized)


I am using postman and I've tried updating a user's profile via http://localhost:8180/auth/admin/realms/demo/users/{userID} but I received a 401 response.

The procedure I used:

Unfortunately, I've received back-to-back 401 responses.

First request:

-Body(x-www-form-urlencoded)

client_id : admin_cli
username: ...
password: ...
grant_type: password
client_secret: ...

-To http://localhost:8180/auth/realms/master/protocol/openid-connect/token

Second request:

-Header -> Authorization: Bearer ...

-Body(JSON)

"email": "d@gmail.com",
"firstName": "divad",
"lastName": "d"

-To http://localhost:8180/auth/admin/realms/demo/users/{userID}


Solution

  • Update: The /auth path was removed starting with Keycloak 17 Quarkus distribution. So you might need to remove the /auth from the endpoint calls presented on this answer.


    In your first call, the david user has to be one with admin-alike privileges. Otherwise, one gets an authorized error response for the actions that the david user does not have the privileges to perform. Have a look at this SO thread to check how to assign admin-alike privileges to a user.

    For now let us request a token on the behalf of the master admin user as follows:

    enter image description here

    from the body response extract the access_token.

    For the second call first, copy and paste the access_token to the Authorization > Type Bearer Token:

    enter image description here

    On the second call, instead of

    http://localhost:8180/auth/admin/realms/demo/users/{userID} 
    

    you need to replace the userID parameter with the actual userID of the user that you are updating. To get userID you can call the following endpoint:

    GET <YOUR_KEYCLOAK_DOMAIN>/auth/admin/realms/<YOUR_REALM>/users/?username=<THE_USERNAME>
    

    or you can copy and paste from the Keycloak Admin Console, under the tab users:

    enter image description here

    So in Postman would look like:

    enter image description here