swagger-typescript-api icon indicating copy to clipboard operation
swagger-typescript-api copied to clipboard

How to use access and refresh tokens from local storage

Open IDriuk opened this issue 3 years ago • 1 comments

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?

IDriuk avatar Jul 15 '22 08:07 IDriuk

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

wirekang avatar Jul 29 '22 08:07 wirekang