Get access token using refresh token with Keycloak

I introduced Refresh Token grant type in OAuth 2.0 in the tutorial about Grant types in OAuth 2.0. In this tutorial, I will show you how we get a new access token using refresh token with Keycloak!

First, I will create a new client in Keycloak with the Authorization Code grant type as an example:

Perform get access token for this client, you will see the following results:

The content of the refresh token if I decode it using https://jwt.io/ is basically as follows:

Please pay attention to the “typ” claim in the content of the refresh token above! Here, the value of this claim is Refresh, we also have some other types of refresh tokens, such as Offline,…

Refresh token will always be returned along with the access token, so we can get a new access token without the user having to log in again.

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.

With this example of mine, you can get a new access token by requesting the following:

As you can see, with the Refresh Token grant type, we don’t need the user to log in anymore.

A refresh token will always have an expiration time, the default of Keycloak is 30 minutes! Every time a new access token is issued, the refresh token will be re-issued, and you can use the latest one for a longer expiration time.

We can use a refresh token to request the access token multiple times. However, you can limit the number of times a refresh token can be used, by going to the Tokens tab of Realm Settings, configuring the Revoke Refresh Token field. If you turn on this field, you can configure how many times a refresh token is reused:

By default, you can only use the refresh token once!

Add Comment