swagger-typescript-api
swagger-typescript-api copied to clipboard
How to use access and refresh tokens from local storage
Hi! Help me, please. How can I use access token from local storage and when it expired how can I get new token with refresh token from local storage , make request to get new token with refresh and use new access token with original request?
I think setSecurityData seems to be related this issue, but I couldn't figure out, so I redefined request method.
const api = new Api()
const oldRequest = api.request // to prevent infinite loop
api.request = async (oldParams) => {
const headers: any = oldParams.headers ?? {}
if ( __HAVE_ACCESS_TOKEN__ ) {
headers.Authorization = `Bearer ${ __ACCESS_TOKEN__ }`
}
const params = { ...oldParams, headers }
try {
const response = await oldRequest(params)
return response
} catch (e) {
if (oldParams.path === __PATH_TO_RENEW_TOKENS__ ) {
__REMOVE_TOKENS__
throw e
}
if ( __ACCESS_TOKEN_IS_EXPIRED_AND_HAVE_REFRESH_TOKEN ) {
const res = await api.__RENEW_TOKEN__
__SAVE_TOKENS__
params.headers.Authorization = `Bearer ${ __NEW_ACCESS_TOKEN__ }`
return oldRequest(params)
}
throw e
}
}
export api