首页 > 解决方案 > 使用访问/刷新令牌和 axios(cookies?本地存储?)进行安全身份验证

问题描述

我正在使用 nodejs 后端构建一个具有访问和刷新令牌的身份验证系统。

目前,我只使用有效期为 24 小时的访问令牌。我将它们设置在服务器上的 httpOnly-cookie 中,仅通过 https 发送(安全:true)。使用 axios,我将 withCredentials-option 添加到请求中,并将 cookie(带有令牌)发送到服务器。

我对 axios 进行了一些调整以使用访问/刷新令牌。到目前为止我的代码:

import axios from 'axios';

const apiUrl = 'http://localhost:5000/api',

// add the accessToken to the request config when making a request
// with axios
axios.interceptors.request.use((config) => {
  const accessToken = localStorage.getItem('accessToken');
  if (accessToken) {
    config.headers['Authorization'] = `Bearer ${accessToken}`;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// check if a status 401 is send back
// this means the access token is invalid
// do a request to the server to refresh the access token with the refresh token
// and repeat the initial request when the new access token is received
axios.interceptors.response((response) => {
  // status 200 OK
  // just return the response
  return response;
}, (error) => {
  // store the original request (passed with the error)
  const origReq = error.config;
  const refreshToken = localStorage.getItem('refreshToken');
  // origReq.retried is just to prevent an infinite loop of retries
  if (refreshToken && !origReq.retried) {
    origReq.tried = true;
    return axios({
      method: 'get',
      url: `${apiUrl}/auth/refresh-access-token`,
      headers: {
        'Authorization': `Bearer ${refreshToken}`
      }
    })
    .then((response) => {
      // store the new access token
      localStorage.setItem('accessToken', response.data.accessToken);
      // retry the original request
      return axios(origReq);
    });
  } else {
    return Promise.reject(error);
  }
);

基本上我创建了 2 个拦截器:1 个用于请求(将访问令牌添加到请求)和 1 个用于响应(检查响应状态,如果状态 = 401 则访问令牌无效,因此请先刷新访问令牌使用刷新令牌)。

关于此代码的一些注意事项:

提前致谢!

标签: javascriptnode.jsreactjsaxios

解决方案


推荐阅读