Vue.js @nuxtjs/auth为什么刷新页面总是重定向到登录

Vue.js @nuxtjs/auth为什么刷新页面总是重定向到登录,vue.js,nuxt.js,Vue.js,Nuxt.js,我无法刷新页面或在刷新后打开安全页面的新选项卡,否则新选项卡会将我重定向到登录 再次 版本 Nuxt.js v2.9.1 @nuxtjs/module: 4.8.4 安全页面 middleware: ['auth'], middleware: ['guest'], auth模块中间件 登录页面 middleware: ['auth'], middleware: ['guest'], 中间件/guest.js export default async function({ store,

我无法刷新页面或在刷新后打开安全页面的新选项卡,否则新选项卡会将我重定向到登录 再次

版本

Nuxt.js v2.9.1
@nuxtjs/module: 4.8.4
安全页面

middleware: ['auth'],
middleware: ['guest'],
auth模块中间件

登录页面

middleware: ['auth'],
middleware: ['guest'],
中间件/guest.js

export default async function({ store, redirect }) {
    // console.log(store.state.auth)
    if (store.state.auth.loggedIn) {
        return redirect('/')
    }
}
auth: {
        strategies: {
            local: {
                endpoints: {
                    // register: { url: 'member', method: 'post', propertyName: 'data.accessToken' },
                    login: { url: 'api/authen-admin', method: 'post', propertyName: 'custom' },
                    user: { url: 'api/admin', method: 'get', propertyName: 'custom' },
                    logout: false
                },
                tokenRequired: 'Authorization',
                tokenType: false
            }
        },
        watchLoggedIn: true,
        localStorage: {
            prefix: 'auth.'
        },
        cookie: {
            prefix: 'auth.', // Default token prefix used in building a key for token storage in the browser's localStorage.
            options: {
                path: '/', // Path where the cookie is visible. Default is '/'.
                expires: 5 // Can be used to specify cookie lifetime in Number of days or specific Date. Default is session only.
                    // domain: '', // Domain (and by extension subdomain/s) where the cookie is visible. Default is domain and all subdomains.
                    // secure - false, // Sets whether the cookie requires a secure protocol (https). Default is false, should be set to true if possible.
            }
        },
        redirect: {
            login: '/login',
            logout: '/login',
            home: '/'
        },
        resetOnError: true
}
console.log(store.state.auth)={user:null,loggedIn:false,策略:'local'}

numxt.config.js

export default async function({ store, redirect }) {
    // console.log(store.state.auth)
    if (store.state.auth.loggedIn) {
        return redirect('/')
    }
}
auth: {
        strategies: {
            local: {
                endpoints: {
                    // register: { url: 'member', method: 'post', propertyName: 'data.accessToken' },
                    login: { url: 'api/authen-admin', method: 'post', propertyName: 'custom' },
                    user: { url: 'api/admin', method: 'get', propertyName: 'custom' },
                    logout: false
                },
                tokenRequired: 'Authorization',
                tokenType: false
            }
        },
        watchLoggedIn: true,
        localStorage: {
            prefix: 'auth.'
        },
        cookie: {
            prefix: 'auth.', // Default token prefix used in building a key for token storage in the browser's localStorage.
            options: {
                path: '/', // Path where the cookie is visible. Default is '/'.
                expires: 5 // Can be used to specify cookie lifetime in Number of days or specific Date. Default is session only.
                    // domain: '', // Domain (and by extension subdomain/s) where the cookie is visible. Default is domain and all subdomains.
                    // secure - false, // Sets whether the cookie requires a secure protocol (https). Default is false, should be set to true if possible.
            }
        },
        redirect: {
            login: '/login',
            logout: '/login',
            home: '/'
        },
        resetOnError: true
}

我尝试使用vuex persist来持久化本地存储,但不起作用,当登录未重定向到主路径时,仍然保持登录路径

也许您可以使用
nuxtServerInit
来检查登录用户。作为根文件夹放置在
store/index.js
文件夹中。每次您第一次打开web时,此代码都将运行。示例我使用cookie检查用户loggedIn与否:

export const actions = {
  async nuxtServerInit ({ commit }, { req }) {
    let auth = null
    if (req.headers.cookie) {
      // cookie found
      try {
        // check data user login with cookie
        const { data } = await this.$axios.post('/api/auths/me')
        // server return the data is cookie valid loggedIn is true
        auth = data // set the data auth
      } catch (err) {
        // No valid cookie found
        auth = null
      }
    }
    commit('SET_AUTH', auth) // set state auth
  },
}

文档

您将用户端点的
propertyName
设置为
'custom'
,是否收到具有此属性名称的响应?重新加载页面时,auth插件将尝试
fetchUser
方法以确保客户端仍然经过身份验证,如果您没有正确配置用户端点,无论是否接收,用户都将设置为null,因此您将重定向到登录页面,您可以通过运行此代码检查用户属性设置:

let user = await this.$auth.requestWith(
    'local', null, { url: 'api/admin', method: 'get', propertyName: 'custom' } );
console.log(user);

扩展Fauzan Edris答案

我在使用Auth-Nuxt,修复了我的问题

export const actions = {
  async nuxtServerInit({
    commit
  }, {
    req
  }) {
    let auth = null
    if (req.headers.cookie) {
      // cookie found
      try {
        // check data user login with cookie
        const {
          data
        } = await this.$axios.post('/user/profile')
        // server return the data is cookie valid loggedIn is true
        auth = data.data // set the data auth
      } catch (err) {
        // No valid cookie found
        auth = null
      }
    }

    // How we can set the user for AuthNuxt
    // Source: https://auth.nuxtjs.org/api/auth
    this.$auth.setUser(auth)
  },
}

我在Laravel Sanctum中使用Nuxt,解决这个问题的是会话域的问题。我正在子域上运行项目,会话域设置为“.DOMAIN.com”,但它必须设置为“sub.DOMAIN.com”。

嘿!我是@VueScreencast的Jeffrey。感谢您制作此文件并添加代码。“我尝试使用vuex persist来持久化本地存储,但不起作用”-两个想法:1。我不必使用额外的库来保存本地存储或cookie。vuex会干涉吗?2.你说“不行”是什么意思?它根本不储存饼干吗?还是存储cookie但不将其发送到服务器?还是将它们发送到服务器,但身份验证是错误的?@JeffreyBiles 1。我不会使用额外的库来制作像你一样的localstrorage或Cookie。2.“不起作用”是指当我使用vuex persist@nuxtjs/auth登录成功时不重定向,但卸载vuex persist,然后当登录成功时@nuxtjs/auth重定向,“vuex persist”是额外的库,并且由于它在卸载vuex persist时起作用,我想我们有了答案。如果您需要将vuex persist用于其他用途,那么您应该询问以前使用过该库的人,因为该漏洞似乎位于vuex persist而不是Nuxt Auth中。很抱歉,让您感到困惑,当我仅使用Nuxt Auth时,它不起作用,无法刷新页面,然后我尝试使用“vuex persist”若要持久化localstorage或cookie,请在登录成功时声明不是空的,而是nuxt auth的错误nuxt auth无法重定向到安全页面