Skip to main content

Access token renewal

When you are developing an application that run for longer than the access token lifetime, you should handle the token renewal. To know when the token should be renewed, the expires_in property in the response of the token endpoint should be used.

A good practice is to use the same token for multiple requests until it is close to expire.

The following code sample implements the access token renewal 10 seconds before its expiration.

import axios, { InternalAxiosRequestConfig } from 'axios';
import { Issuer, TokenSet } from 'openid-client'

const authenticator = (client_id: string, client_secret: string, token_endpoint: string) => {
let tokenSet: null | TokenSet = null;

const issuer = new Issuer({
issuer: "",
token_endpoint,
});

const client = new issuer.Client({
client_id,
client_secret,
});

return async (config: InternalAxiosRequestConfig) => {
if (tokenSet == null || (tokenSet.expires_in ?? 0) < 10) {
tokenSet = await client.grant({
grant_type: 'client_credentials'
});
}
config.headers.Authorization = `Bearer ${tokenSet.access_token}`;
return config;
}
}

const instance = axios.create({
baseURL: 'https://<platform-hostname>',
});

instance.interceptors.request.use(authenticator(
'<client-id>',
'<client-secret>',
"https://<platform-hostname>/users-auth/protocol/openid-connect/token",
));

const devices = await instance.get('/thingpark/wireless/rest/subscriptions/mine/devices');