Offline access is a feature of OpenID Connect defined at https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess. It allows the application with an offline token (a kind of refresh token) to get access token and use resources without the user having to log in, for a long time or forever. Keycloak supports us to work with offline access using offline tokens. How is it in detail? Let’s find out together in this tutorial!
As an example, I will create a new client with the grant type Authorization Code in Keycloak as follows:
The first thing you need to know is how we get the offline token.
Very simply, in the request to get the authorization code for the client, we need to pass an additional scope of offline_access:
Keycloak will ask if we allow Client Application Offline Access or not?
If you agree, after having the authorization code, request to get the access token for this client:
parse the content of the refresh token, you will see the payload content as follows:
The type of this token is Offline instead of Refresh and you can see, there is no “exp” claim with expiration time like when we parse the access token:
We can use this offline token to get a new access token similar to a refresh token.
Example is as follows:
The difference between an offline token and a refresh token is that there is no expiration time for an offline token.
By default, the offline token is valid even if the user is not logged in or the server is restarted, unless it is revoked. However, you need to use this offline token at least once within the default period of 30 days from the last use. That’s because an offline token will associate with an offline session. And this offline session only has the default idle time of 30 days as I said above. At the Realm level, this 30-day value is configured in the Tokens tab of Realm Settings, the Offline Session Idle field:
In this Tokens tab, as you can see, we have another field related to offline sessions, named Offline Session Max Limited. The meaning of this field is that if you enable it, the offline token will be expired in the default time of 60 days, no matter how many times we use this offline token:
You can change the configuration related to the offline session at the Realm level if you want, clients will inherit this configuration. If you want to configure specifically for a certain client, expand the Advanced Settings section in each client:
we can change the configuration of Client Offline Session Idle and Client Offline Session Max here.
You can view all the offline tokens of a client by going to that client’s Offline Access tab: