在 Nuxt Auth 中设置会话 ID Cookie

Dom*_*och 6 django nuxt.js

我在我的 nuxt.config.js 文件中设置了以下内容:

auth: {
redirect: {
  login: '/accounts/login',
  logout: '/',
  callback: '/accounts/login',
  home: '/'
},
strategies: {
  local: {
    endpoints: {
      login: { url: 'http://localhost:8000/api/login2/', method: 'post' },
      user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' },
      tokenRequired: false,
      tokenType: false
    }
  }
},
localStorage: false,
cookie: true
},
Run Code Online (Sandbox Code Playgroud)

我在身份验证后端使用 django 会话,这意味着成功登录后,我将在响应 cookie 中收到会话 ID。但是,当我使用 nuxt 进行身份验证时,我在响应中看到了 cookie,但未保存 cookie 以供进一步请求使用。知道我还需要做什么吗?

tim*_*123 5

这就是我处理这个的方式,它来自一个我找不到的论坛帖子。首先摆脱 nuxt/auth 并使用 vuex 商店推出自己的。您将需要两个中间件,一个应用于要进行身份验证的页面,另一个用于相反的页面。

这假设您有一个配置文件路由和一个登录路由,在成功登录时返回用户 json。

我还将用户写入名为 authUser 的 cookie,但这仅用于调试,如果您不需要,可以将其删除。

存储/索引

import state from "./state";
import * as actions from "./actions";
import * as mutations from "./mutations";
import * as getters from "./getters";

export default {
  state,
  getters,
  mutations,
  actions,
  modules: {},
};
Run Code Online (Sandbox Code Playgroud)

存储/状态

export default () => ({
  user: null,
  isAuthenticated: false,
});
Run Code Online (Sandbox Code Playgroud)

存储/操作

export async function nuxtServerInit({ commit }, { _req, res }) {
  await this.$axios
    .$get("/api/users/profile")
    .then((response) => {
      commit("setUser", response);
      commit("setAuthenticated", true);
    })
    .catch((error) => {
      commit("setErrors", [error]); // not covered in this demo
      commit("setUser", null);
      commit("setAuthenticated", false);
      res.setHeader("Set-Cookie", [
        `session=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
        `authUser=false; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
      ]);
    });
}
Run Code Online (Sandbox Code Playgroud)

存储/突变

export const setUser = (state, payload) => (state.user = payload);
export const setAuthenticated = (state, payload) =>
  (state.isAuthenticated = payload);
Run Code Online (Sandbox Code Playgroud)

存储/吸气剂

export const getUser = (state) => state.user;
export const isAuthenticated = (state) => state.isAuthenticated;
Run Code Online (Sandbox Code Playgroud)

中间件/重定向IfNoUser

export default function ({ app, redirect, _route, _req }) {
  if (!app.store.state.user || !app.store.state.isAuthenticated) {
    return redirect("/auth/login");
  }
}
Run Code Online (Sandbox Code Playgroud)

中间件/重定向IfUser

export default function ({ app, redirect, _req }) {
  if (app.store.state.user) {
    if (app.store.state.user.roles.includes("customer")) {
      return redirect({
        name: "panel",
        params: { username: app.store.state.user.username },
      });
    } else if (app.store.state.user.roles.includes("admin")) {
      return redirect("/admin/dashboard");
    } else {
      return redirect({
        name: "panel",
      });
    }
  } else {
    return redirect("/");
  }
}
Run Code Online (Sandbox Code Playgroud)

页面/登录-登录方式

async userLogin() {
  if (this.form.username !== "" && this.form.password !== "") {
    await this.$axios
      .post("/api/auth/login", this.form)
      .then((response) => {
        this.$store.commit("setUser", response.data);
        this.$store.commit("setAuthenticated", true);
        this.$cookies.set("authUser", JSON.stringify(response.data), {
          maxAge: 60 * 60 * 24 * 7,
        });
        if (this.$route.query.redirect) {
          this.$router.push(this.$route.query.redirect);
        }
        this.$router.push("/panel");
      })
      .catch((e) => {
        this.$toast
          .error("Error logging in", { icon: "error" })
          .goAway(800);
Run Code Online (Sandbox Code Playgroud)