在Nuxt Auth中设置会话ID Cookie

时间:2020-03-30 21:43:03

标签: 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
},

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

2 个答案:

答案 0 :(得分:2)

这就是我处理此问题的方式,该信息来自一个我后来找不到的论坛帖子。首先摆脱nuxt / auth并使用vuex store推出自己的产品。您将需要两种中间件,一种适用于您要进行身份验证的页面,另一种适用于相反的情况。

这假设您具有个人资料路由和登录路由,并在成功登录后返回用户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: {},
};

商店/州

export default () => ({
  user: null,
  isAuthenticated: false,
});

商店/动作

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`,
      ]);
    });
}

商店/变更

export const setUser = (state, payload) => (state.user = payload);
export const setAuthenticated = (state, payload) =>
  (state.isAuthenticated = payload);

商店/吸气者

export const getUser = (state) => state.user;
export const isAuthenticated = (state) => state.isAuthenticated;

中间件/ redirectIfNoUser

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

中间件/ redirectIfUser

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("/");
  }
}

页面/登录登录方法

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);

答案 1 :(得分:0)

cookie 由服务器发送,但客户端不会读取它,直到您在客户端请求 (about withCredentials read here) 中设置属性 withCredentials

要解决您的问题,您必须使用 withCredentials 属性扩展您的身份验证配置。

    endpoints: {
      login: { 
        url: 'http://localhost:8000/api/login2/', 
        method: 'post'
        withCredentials: true 
      }
    }

同样不要忘记在您的服务器上设置 CORS 策略以支持 cookie 交换

来自 ExpressJS 的示例

app.use(cors({ credentials: true, origin: "http://localhost:8000" }))

有关此问题的更多信息,请访问 auth-module github

相关问题