0

我正在尝试在 vuejs 3 中实现身份验证。我将 django 和 django 作为后端和用于生成令牌的简单 jwt。一切正常。生成的令牌就是这种格式。 在此处输入图像描述

这是我的身份验证商店,顺便说一下,我使用的是 axios 和 vuex

import axios from "axios";
import { API_ENDPOINTS } from "../../constants/API";

const authStore = {
  state: {
    status: "",
    access_token: localStorage.getItem("access_token") || "",
    refresh_token: localStorage.getItem("refresh_token") || "",
  },
  mutations: {
    auth_request(state) {
      state.status = "loading";
    },
    auth_success(state, access_token, refresh_token, user) {
      state.status = "success";
      state.access_token = access_token;
      state.refresh_token = refresh_token;
      state.user = user;
    },
    auth_error(state) {
      state.status = "error";
    },
    logout(state) {
      state.status = "";
      state.access_token = "";
      state.refresh_token = "";
    },
  },
  actions: {
    login({ commit }, user) {
      return new Promise((resolve, reject) => {
        commit("auth_request");
        axios({
          url: API_ENDPOINTS.CREATE_TOKEN,
          data: user,
          method: "POST",
        })
          .then((resp) => {
            console.log(resp);
            const access_token = resp.data.access;
            const refresh_token = resp.data.refresh;
            const user = resp.data.user;
            localStorage.setItem("access_token", access_token);
            localStorage.setItem("refresh_token", refresh_token);
            axios.defaults.headers.common[
              "Authorization"
            ] = `Bearer ${access_token}`;
            commit("auth_success", access_token, refresh_token, user);
            resolve(resp);
          })
          .catch((err) => {
            commit("auth_error");
            localStorage.removeItem("access_token");
            localStorage.removeItem("refresh_token");
            reject(err);
          });
      });
    },
    logout({ commit }) {
      // eslint-disable-next-line no-unused-vars
      return new Promise((resolve, reject) => {
        commit("logout");
        localStorage.removeItem("access_token");
        localStorage.removeItem("refresh_token");
        delete axios.defaults.headers.common["Authorization"];
        resolve();
      });
    },
  },
  getters: {
    isLoggedIn: (state) => !!state.access_token,
    authStatus: (state) => state.status,
  },
};

export default authStore;

上面的代码工作正常,唯一的问题是每当我刷新页面时,我都无法执行任何操作,比如获取或发布。

甚至令牌在本地存储中也可用。

注意:-我认为我缺少刷新令牌之类的东西,我认为我需要使用刷新令牌,但我不知道如果刷新令牌有问题,我该如何使用刷新令牌。

在此处输入图像描述

4

1 回答 1

0
axios.defaults.headers.common[
              "Authorization"
            ] = `Bearer ${access_token}`;

用户登录时不会调用此代码,因此也许您应该在本地存储中的令牌可用时调用它。

于 2021-01-24T09:37:58.157 回答