【问题标题】:Set Session ID Cookie in Nuxt Auth在 Nuxt Auth 中设置 Session ID Cookie
【发布时间】:2020-03-30 21:43:03
【问题描述】:

我的 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 以用于进一步的请求。知道我还需要做什么吗?

【问题讨论】:

    标签: django nuxt.js


    【解决方案1】:

    这就是我处理这个问题的方式,它来自一个我找不到的论坛帖子。首先摆脱 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: {},
    };
    

    存储/状态

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

    pages/login- 登录方式

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

    【讨论】:

      【解决方案2】:

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

      要解决您的问题,您必须使用 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

      【讨论】:

        猜你喜欢
        • 2021-09-11
        • 2014-10-10
        • 1970-01-01
        • 2022-01-15
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 2019-03-05
        • 2015-11-29
        相关资源
        最近更新 更多