Refresh Token

Learn about refresh token, how to get a refresh token and how to use it to get a new access token.

In Authgear, a refresh token is a key that our authorization server returns when an OAuth 2.0 client application successfully exchanges an authorization code for an access token. Usually, in OAuth 2.0, access tokens expire after some time (you can configure this time in the Authgear portal). The refresh token exists to allow your application to request a new access token after the previous one has expired. It eliminates the need for your user to repeat the entire login process all over.

In this post, we'll teach you how to get a refresh token and how to use it to request a new access token after the old one has expired.

Pre-requisite

  • This post assumes you already have some experience with using Authgear as an OIDC provider.

  • Have an Authgear account and an Authgear application.

  • Have the configuration (client ID, authorized redirect URI, endpoints, etc) of your Authgear application noted down.

If you are completely new to Authgear, check out one of our getting started guides first.

How to Get A Refresh Token

There are many ways to implement Authgear as an Open ID Connect (OIDC) provider for your application based on the programming language or framework you're using. This may determine the procedure you follow to get a refresh token. For example, if you're using any of our official SDKs, there are built-in methods and configurations that simplify the process of getting a refresh token and renewing an expired access token.

However, the key thing that all implementations have in common is including the following scope parameter to your application authorization URL:

scope=openid+offline_access

Or just scope=offline_access.

Example of Authgear token endpoint response with refresh token included:

{
  "access_token": "Rjr3abcD1234UVWXYZ1lt",
  "expires_in": 1800,
  "id_token": "eyKdsdj88sdjsdjjdfjjdfjdfjdfjkskslslslmd.eyshdhsdhnsjdksdjd7783jdjed83hd.VR848348384dd-atjdjdfjdfjsnsn-hhsdjsdjsjdjsdj-wuUb0-kb88usdusdjsjdjsdjsdsd-dddddss-kjdhdhfhdhfhhdfh3he34h",
  "refresh_token": "5385267f-24a8-4fcf-9561-0380602868e2.Z8vxeBZ6TXXOmgsc8GUALnN9puxuqcqy",
  "token_type": "Bearer"
}
  • The refresh_token field contains the refresh token.

  • expires_in is how long (seconds) an access token is valid before it expires.

The following steps show an example of how to get a refresh token from Authgear with some common languages and frameworks.

Step 1: Add Authgear Configuration to Your Code

For this step, log in to the Authgear Portal, navigate to the Applications section, and select your application. copy the configuration details for your application into your code as shown below:

For this React example, we are using the official Authgear JavaScript SDK. Install it using the following command:

npm install @authgear/web
import authgear from "@authgear/web";

export const endpoint = ""; // The Authgear endpoint of your project e.g. https://my-app.authgearapps.com
export const clientID = ""; // Client ID can be obtained in the "Applications" page of the Portal

async function init() {
  try {
    await authgear.configure({
      endpoint,
      clientID,
      sessionType: "refresh_token"
    });
  } finally {
    createRoot(document.getElementById("react-app-root")!).render(<App />);
  }
}

// eslint-disable-next-line no-console
init().catch((e) => console.log(e));

Because the SDK can handle the task of getting a refresh token and using it to renew an access token, you do not need to specify the offline scope in your configuration.

Step 2: Get Refresh Token From Token Endpoint

Authgear will return the refresh token along with the access token when your application makes an HTTP request to the /oauth2/token endpoint, provided you include the offline_access scope as shown in step 1.

Note: Authgear will omit refresh token if your initial request to the authorize URL does not include the offline_access scope.

The following code examples show how to make a request to the token endpoint and get the refresh token from the response JSON object.

As mentioned earlier the Authgear JavaScript SDK can handle the task of getting the refresh token and using it to renew the access token when necessary. The following code shows how to call the method:

authgear
    .refreshAccessTokenIfNeeded()
    .then(() => {
        // access token is ready to use
        // accessToken can be string or undefined
        // it will be empty if user is not logged in or session is invalid
        const accessToken = authgear.accessToken;

        // include Authorization header in your application request
        const headers = {
            Authorization: `Bearer ${accessToken}`
        };
    });

Summary

To get a refresh token from Authgear, you need to include offline_access in your authorization request.

The Authgear SDKs take care of getting refresh token and you do not need to do any extra configuration.

It is recommended to store the refresh token securely on the user's device and use it to request a new access token when the current one expires.

Last updated

#311: Include export users api in api reference doc page

Change request updated