Search code examples
phpdockerkeycloakkeycloak-serviceskeycloak-admin-cli

How to verify a user's email when adding a new user with add-user-keycloak.sh?


We are currently adding default Keycloak users in the following way:

/opt/jboss/keycloak/bin/add-user-keycloak.sh -r realm-name -u [email protected] -p admin

However, when I attempt to generate a bearer token like this:

curl --location --request POST 'http://auth.server-name.localhost/auth/realms/realm-name/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode '[email protected]' \
--data-urlencode 'password=admin' \
--data-urlencode 'client_id=my-clien-id'

I get the following error response:

{"error":"invalid_grant","error_description":"Account is not fully set up"}

From searching I've found this is due to the user email not being verified.

Is there any way that I can verify the user, perhaps by passing an emailVerified parameter to add-user-keycloak.sh or something similar?


Solution

  • Since this will be used in a testing environment, you can use Keycloak Admin CLI tool. The script is kcadm.sh in Linux and kcadm.bat in Windows, both under Keycloak's standalone installation bin folder. First, you need to get the list of users:

    ./kcadm.sh get users
    

    Then, from the output of that command, you extract the ID (let us named lets called <USER_ID>) of the user that you want to set the Email Verified as ON.

    Then, you just have to execute:

    ./ kcadm.sh update users/<USER_ID> -s 'emailVerified=true'
    

    The other option is to use Keycloak Admin REST API

    The first step is to get an admin token, so that you can call the Rest API:

    curl    -d "client_id=admin-cli" \
            -d "username=$ADMIN_NAME" \
            -d "password=$ADMIN_PASSWORD" \
            -d "grant_type=password" \
            https://$KEYCLOAK_IP/auth/realms/master/protocol/openid-connect/token
    

    You will get a json response with the admin token. Extract the access token from that response (lets called $ACCESS_TOKEN).

    Second, you need to get the user ID, lets called $USER_ID.

    curl -X GET https://$KEYCLOAK_IP/auth/admin/realms/$USER_REALM/users/?username=$USERNAME \
        -H "Content-Type: application/json" \
        -H "Authorization: bearer $ACCESS_TOKEN"
    

    Extract from the json response the user ID, and change the email verification by calling:

    curl -k -sS -X PUT https://$KEYCLOAK_IP/auth/admin/realms/$USER_REALM/users/$USER_ID \
            -H "Content-Type: application/json" \
            -H "Authorization: bearer $ACCESS_TOKEN" \
            -d '{"emailVerified":true}'