Access Keycloak APIs using Two-Factor Authentication

How To Access Keycloak APIs Using Two-Factor Authentication

Two-Factor Authentication is the very strong and recommended security control.

In my previous post I have described how to configure Two-factor authentication in Keycloak.

The short (but important) post describes how to access Keycloak APIs using Two-Factor Authentication.

Access Keycloak APIs Using User Name and Password

Let’s first access Keycloak APIs Using User Name and Password.

According to the Keycloak documentation, you first need to obtain an access token. (The access token itself is OAuth 2.0 token.)

Replace <username> and <password> with real user credentials and invoke the following command:

curl
-d “client_id=admin-cli”
-d “username=<username>
-d “password=<password>
-d “grant_type=password”
http://localhost:8080/auth/realms/master/protocol/openid-connect/token

You will get a JSON document in a response. Extract the value of the access_token property.

{“access_token”:“ey...g”,“expires_in”:3600,“refresh_expires_in”:1800,“refresh_token”:“ey...Q”,“token_type”:“bearer”,“not-before-policy”:0,“session_state”:“4…d”}

Replace <access_token> with real token value and invoke the following command. The example below will get accessible realms.

You can find all rest APIs in Keycloak documentation.

curl
-H “Authorization: bearer <access_token>
http://localhost:8080/auth/admin/realms"

The example of JSON response:

[{“id”:“master”,“realm”:“master”,“displayName”:“Keycloak”,...}]

Access Keycloak APIs Using Two-Factor Authentication

Let’s configure a user to use Two-factor authentication according to my previous post.

If you will run the same command to obtain an access token it will fail:

curl
-d “client_id=admin-cli”
-d “username=<username>
-d “password=<password>
-d “grant_type=password”
http://localhost:8080/auth/realms/master/protocol/openid-connect/token

The error response

{“error”:“invalid_grant”,“error_description”:“Invalid user credentials”}

What we need to do?

🤔

The parameter totp will do the magic!

Obtain the one time token from your OTP authenticator, replace <one time token> below and invoke the command:

curl -k
-d “client_id=admin-cli”
-d “username=<username>
-d “password=<password>
-d “totp=<one time token>
-d “grant_type=password”
http://localhost:8080/auth/realms/master/protocol/openid-connect/token

The command will return the access token, and you will be able to invoke Keycloak APIs.

Enjoy Access Keycloak APIs Using Two-Factor Authentication