Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To update a username in Keycloak using its API, follow these steps:

  1. Obtain an access token from Keycloak using the client credentials or user authentication flow.
  2. Make a PUT request to the /users/{id} endpoint, where {id} is the ID of the user whose username you want to update.
  3. In the request body, include the new username in the username field.
  4. Set the Authorization header to Bearer {access_token}, where {access_token} is the token obtained in step 1.

Here's an example of how to update a user's username using the Keycloak API in Python:

import requests
import json

# obtain access token
url = "http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token"
payload = {
    "grant_type": "client_credentials",
    "client_id": "myclient",
    "client_secret": "mysecret"
}
response = requests.post(url, data=payload)
access_token = response.json().get("access_token")

# update username
user_id = "12345-67890"  # the ID of the user to update
username = "newusername"  # the new username
url = f"http://localhost:8080/auth/admin/realms/myrealm/users/{user_id}"
payload = {
    "username": username
}
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}
response = requests.put(url, data=json.dumps(payload), headers=headers)
response.raise_for_status()

Note that the Content-Type header must be set to application/json for the request body to be recognized as JSON. Additionally, the user making the API request must have the necessary permissions to update users in Keycloak.