T
T
Troodi Larson2019-12-14 17:18:36
Vue.js
Troodi Larson, 2019-12-14 17:18:36

How to check for 401?

Good afternoon, I'm trying to complete the authorization. There is a login api itself, and if it doesn’t work, we try to get a refresh token using the old one. Using interceptors, everything hangs because the same 401 error handling is used again. And if the token is not valid at all, then 401 will be returned for her as well. I can't figure out how best to process exactly the refresh-token address if there is a 401 error. I haven't been able to get it right for a week. Give advice?
That is, you need to somehow return an error for the request token refresh, if there is 401.

import axios from "../../../axios/index.js"
import store from "../../../../store/store.js"

// Token Refresh
let isAlreadyFetchingAccessToken = false
let subscribers = []
let tokenIsValidAndFethed = false;

function onAccessTokenFetched(access_token) {
  localStorage.setItem("accessToken", access_token);
  subscribers = subscribers.filter(callback => callback(access_token))
}

function addSubscriber(callback) {
  subscribers.push(callback)
}

export default {
  init() {
    axios.interceptors.response.use(function (response) {
      return response
    }, function (error) {
      // const { config, response: { status } } = error
      const { config, response } = error;
      const originalRequest = config;

      // if (status === 401) {
      if (response && response.status === 401) {
        if (!isAlreadyFetchingAccessToken) {
          isAlreadyFetchingAccessToken = true
          store.dispatch("auth/fetchAccessToken")
            .then((access_token) => {
              isAlreadyFetchingAccessToken = false
              onAccessTokenFetched(access_token.data.access_token)
            })
        }

        const retryOriginalRequest = new Promise((resolve) => {
          addSubscriber(access_token => {
              originalRequest.headers.Authorization = 'Bearer ' + access_token;
              resolve(axios(originalRequest))
          })
        });
        return retryOriginalRequest;
      }
      return Promise.reject(error)
    })
  },
  login(email, pwd) {
    return axios.post("/api/auth/login", {email: email, password: pwd}, {
        headers: { Authorization: "Bearer " + localStorage.getItem("accessToken") ? localStorage.getItem("accessToken") : ""}
    })
  },
  registerUser(name, email, pwd) {
    return axios.post("/api/auth/register", {displayName: name, email: email, password: pwd})
  },
  refreshToken() {
    return axios.post("/api/auth/refresh-token", {}, {
        headers: { Authorization: "Bearer " + localStorage.getItem("accessToken") ? localStorage.getItem("accessToken") : ""}
    })
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question