Search code examples
single-sign-onkeycloak-rest-api

Latest keycloak server v21.0.0 admin api - create a realm failed


Keycloak server v21.0.0 - Windows 10 - Admin API - create realm failed How i fix the issue? what will be the issue? please help/support

start the server in dev mode

set KEYCLOAK_ADMIN=admin
set KEYCLOAK_ADMIN_PASSWORD=admin
.\kc.bat start-dev --http-port 4444

admin-cli - to get the access token

curl -L -X POST "http://localhost:4444/realms/master/protocol/openid-connect/token" ^
-H "Content-Type: application/x-www-form-urlencoded" ^
--data-urlencode "client_id=admin-cli" ^
--data-urlencode "grant_type=password" ^
--data-urlencode "username=admin" ^
--data-urlencode "password=admin"

I got the access token and using that token here

set TOKEN="eyJh..."

To create a realm

curl --silent --show-error -L -X POST "http://localhost:4444/admin/realms" ^
-d "{\"realm\" : \"test-realm\"}" ^
-H "Content-Type: application/json" ^
-H "Authorization: Bearer %TOKEN%"

Error Response {"error":"HTTP 401 Unauthorized"}


Solution

  • The reason is the master access token's Lifespan is one minute as default.

    It is easy expired during you assign the Token environment variable and call to create realm.

    enter image description here

    So you needs to more time when you debugging or manual REST API calling by curl.

    enter image description here

    And this curl command makes reduce to copy/paste the token from first get token to assign environment variable.

    I am using git bash and jq for windows.

    #1 launching Keycloak 21.0.0 by docker

    docker run -p 4444:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:21.0.0 start-dev
    

    #2 Get Master Access Token and assign into MASTER_TOKEN variable.

    MASTER_TOKEN=$(curl --silent --location --request POST "http://localhost:4444/realms/master/protocol/openid-connect/token" \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'client_id=admin-cli' \
    --data-urlencode 'grant_type=password' \
    --data-urlencode 'username=admin' \
    --data-urlencode 'password=admin' | jq -r '.access_token')
    echo $MASTER_TOKEN
    

    enter image description here

    #3 Create realm

    curl --silent --show-error -L -X POST "http://localhost:4444/admin/realms" \
    -d "{\"realm\" : \"test-realm\"}" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer ""$MASTER_TOKEN"
    

    enter image description here

    Result

    enter image description here