15

Is it possible to update the value of custom attribute via Keycloak REST API? For example, which endpoint to use and how to construct a request body for the attribute that was created here.

Thanks!

avocadoLambda
  • 1,332
  • 7
  • 16
  • 33
kvitaliy
  • 191
  • 1
  • 2
  • 5

3 Answers3

15

You have to use Keycloak Admin REST API :

PUT {host}/{basepath}/admin/realms/{realm}/users/{id}

e.g. http://localhost:8080/auth/admin/realms/alumni-realm/users/cd57cfd8-cb1c-4025-abfd-67fe6b784d22

Request Body (JSON) :

{
    "attributes": {
        "DOB": "1984-07-01"
    }
}

Authorization (Bearer Token) :

  1. Use Admin user access_token for authorization.

  2. If you want to allow User to update their own profile then you have to grant manage-users role in Keycloak. (That user will be able to update other users info hence it is not recommended)

srp
  • 619
  • 7
  • 18
  • 2
    I tested this solution and it works. Kind of. It has one major flaw that bothers me. You're effectively overwriting all existing attributes with new one. Is there a way to just create or update a single attribute? I couldn't find anything in documentation and I'm not a big fan of making 2 requests for this – Smerk Jun 22 '21 at 13:07
  • As of today, I don't see any such api available to update just single attribute. To update single/multiple attributes use payload like given below: `{"attributes": { "attribute_1": "new value","attribute_2": "existing value"}}` – srp Jun 23 '21 at 09:20
  • 2
    If you add the attribute you want to create or update at the end of the attributes map (that you got from the response of the GET call), Keycloak will consider the new value if the added attribute already exists otherwise it will just be added. This will not prevent you from doing 2 calls, but will make simplest the construction of the attributes collection that you will put in the PUT call. { "attributes": { "broker": "12345678", "lang": "FR", "lang": "EN" } } --> the attribute lang will have the "EN" value at the end. – Helali Jun 23 '21 at 17:19
  • More info about obtaining the token here: https://www.keycloak.org/docs/latest/server_development/index.html#admin-rest-api – Joseph Garrone May 19 '22 at 15:05
2

You can use the API for user update with sending only the attribute to be changed:

PUT ../realms/{realm}/users/{userID} Body:

{
    "attributes": {
        "myAttribute": [
            "NewValue"
        ]
    }
}
0

It Cause "ID" change when you update user custom attribute via Keycloak REST API PUT ../realms/{realm}/users/{userID}

and you need to GET /{realm}/users two times to get new value in the response