Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh access_token via refresh_token in Keycloak

I need to make the user keep login in the system if the user's access_token get expired and user want to keep login. How can I get newly updated access_token with the use of refresh_token on Keycloak?

I am using vertx-auth for the auth implementation with Keycloak on vert.x. Is it possible to refresh access_token with vertx-auth or Keycloak's REST API itself? Or what will be another implementation of this?

like image 456
RaiBnod Avatar asked Jul 17 '18 16:07

RaiBnod


People also ask

How do you refresh a Keycloak token?

To get a new access token with a refresh token, in the request to get the access token, you just need to pass grant_type=refresh_token, the value of the refresh token that we had in the previous request to get the access token, client ID and client secret.

How do I specify refresh tokens lifespan in Keycloak?

The refresh tokens lifespan is defined by the "Client Session Max" parameter in the "Tokens" tab of the Realm settings. It can also be overridden on individual clients level under the "Advanced Settings" menu of the client settings page. The maximum time before a refresh token is expired and invalidated.

How do you refresh access tokens?

To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.

What is the best way to store refresh token?

If your application uses refresh token rotation, it can now store it in local storage or browser memory. You can use a service like Auth0 that supports token rotation.


2 Answers

keycloak has REST API for creating an access_token using refresh_token. It is a POST endpoint with application/x-www-form-urlencoded

Here is how it looks:

Method: POST URL: https://keycloak.example.com/auth/realms/myrealm/protocol/openid-connect/token Body type: x-www-form-urlencoded Form fields:     client_id : <my-client-name> grant_type : refresh_token refresh_token: <my-refresh-token> 

This will give you new access token using refresh token.

NOTE: if your refresh token is expired it will throw 400 exception in that you can make user login again.

Check out a sample in Postman, you can develop and corresponding API using this.

Sample in Postman

like image 182
Yogendra Mishra Avatar answered Oct 08 '22 17:10

Yogendra Mishra


@maslick is correct you have to supply the client secret too, no need for authorization header in this case:

http://localhost:8080/auth/realms/{realm}/protocol/openid-connect/token

enter image description here

In case of expired refresh token it returns:

enter image description here

If you don't add the secret you get 401 unauthorized even though the refresh token is correct

enter image description here

like image 22
Khalifa Avatar answered Oct 08 '22 15:10

Khalifa