spotty-amberS
Refine4y ago
39 replies
spotty-amber

How to implement jwt authentication in authProvider?

I have followed this link https://refine.dev/docs/api-reference/core/providers/auth-provider/#setting-authorization-credentials to set my authorization credentials and it is working fine. But now how do I use a refresh token to generate a new access token on every request.

What I have done so far is below:
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const prevRequest = error?.config;
    if (error?.response?.status === 401 && !prevRequest?.sent) {
      prevRequest.sent = true;
      axiosInstance.post(
        `${API_BASE_URL}/token/refresh/`,
        { refresh: localStorage.getItem(TOKEN_REFRESH_KEY) }
      ).then((res => {
        prevRequest.headers = { ...prevRequest.headers, ...authHeader(res.data.access) };
        return axiosInstance(prevRequest);
      }))
      .catch((err) => {
        if(err.response.status === 401) {
          sessionStorage.removeItem(TOKEN_KEY);
          return Promise.reject(new Error('Your login session expired. Please login again.'));
        }
        return Promise.reject(err);
      });
    }
    const customError: HttpError = {
      ...error,
      message: error.response?.data?.message,
      statusCode: error.response?.status,
    };
    return Promise.reject(customError);
  },
);

After using this code I can get new access token there isn't any problem. But once the refresh token is expired then how can I logout user. By using above code the request for refresh token is request infinitely.
refine let's you set authentication logic by providing the authProvider property to the `` component.
Auth Provider | refine
Was this page helpful?