exportkeycloak

Export users and roles from Keycloak


I created users and roles in Keycloak which I want to export.

When I tried to export them using the realm's "Export" button in UI I got a JSON file downloaded.

enter image description here

But I couldn't find any users or roles in the exported file realm.json

How can I export a realm JSON including users and roles from Keycloak?


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.


    You will not be able to do that using the export functionality. However, 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, but later I will explain how you can use another user:

    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 list of users from your realm $REALM_NAME:

    curl -X GET https://$KEYCLOAK_HOST/auth/admin/realms/$REALM_NAME/users \
         -H "Content-Type: application/json" \
         -H "Authorization: bearer $ACCESS_TOKEN"
    

    To get the realm roles:

    curl -X GET https://$KEYCLOAK_HOST/auth/admin/realms/$REALM_NAME/roles \
         -H "Content-Type: application/json" \
         -H "Authorization: bearer $ACCESS_TOKEN"
    

    Now you just need to save the JSON responses from those endpoints into JSON files.

    Assigning the proper user permissions

    For those that do not want to get an access token from the master admin user, you can get it from another user but that user needs the permission view-users from the realm-management client. For that you can:

    (OLD Keycloak UI)

    (New Keycloak UI)