I have a requirement where I need to get an access token of a user.
I am aware of the admin username and password and hence can get the access token of the admin.
Is there any rest API that can provide me access token a user using the above data?
I have a requirement where I need to get an access token of a user.
I am aware of the admin username and password and hence can get the access token of the admin.
Is there any rest API that can provide me access token a user using the above data?
There are two ways to get access token. One with Rest client (keycloak Rest API) and other through java keycloak-admin-client library.
1. Keycloak Rest API:
URI: http://keycloak:8080/auth/realms/myrealm/protocol/openid-connect/token
Type: POST
Content-Type: application/x-www-form-urlencoded
grant_type:password
username:user
password:user_password
client_id:client_id
secret_id:client_secret
2. Keycloak admin client (JAVA)
Keycloak instance = Keycloak.getInstance("http://keycloak:8080/auth", "myrealm", "user", "user_password","client_id", "client_secret");
TokenManager tokenmanager = instance.tokenManager();
String accessToken = tokenmanager.getAccessTokenString();
2023 update to @Sarang's answer
Newer versions of Keycloak do not include /auth/ in the url. And secret_id should be client_secret.
I have the same requirement, however we dont want to pass this Clear Text Password in either of the above approach. We are thinking following approach but want suggesting if any best practices are already in place.
Step-1: Create a secured end point at server end to return token from Keycloak.
Step-2: While calling this end point first, Encrypt the password using some shared key at client end.
Step-3. At the receiving/server end decrypt the password with same shared key.
Step-4. Fetch the token from KeyCloak at server end and return it.
If there are any other better approach, we should follow.