用户总是在nuxt.js auth中刷新时重定向到登录



我用@Nuxt/auth安装了一个Nuxt应用程序。每当刷新页面时,用户总是被重定向到登录页面。我猜Nuxt应用程序的服务器端未登录,而客户端已登录

auth: {
redirect: {
login: '/',
logout: '/',
home: '/dashboard',
},
resetOnError: true,
rewriteRedirects: true,
strategies: {
local: {
token: {
property: 'data.accessToken',
},
user: {
property: 'data[0]',
autoFetch: false,
},
endpoints: {
login: {
url: '/api/v1/users/login',
method: 'post',
},
logout: false,
user: {
url: '/api/v1/users',
method: 'get',
propertyName: false,
},
},
},
},
},

还有我的仪表板.vue

export default {
middleware: ['auth'],

};

这是我的工作nuxt.config.js

export default {
router: {
middleware: ['auth'],
},
modules: [
'@nuxtjs/auth-next'
],
auth: {
redirect: {
login: '/login',
home: '/',
logout: '/login',
callback: false, // not used here in our case
},
localStorage: false, // REALLY not secure, so nah
resetOnError: true, // kick the user if any error happens w/ the auth
strategies: {
local: {
scheme: 'refresh', // used for the refreshToken flow
token: {
property: 'access_token',
maxAge: 3600, // only useful if not detected on the login
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30, // 1 month
},
clientId: process.env.IAM_CLIENT_ID, // our application's ID aka browser
user: {
property: 'employee',
autoFetch: false, // no need to fetch the user, will be done in gql
},
endpoints: {
login: { url: '/login', method: 'post' },
refresh: { url: '/oauth/refresh', method: 'post' },
user: false, // as told above, this one is not needed
logout: { url: '/logout', method: 'get' },
},
tokenRequired: true,
tokenType: 'JWT',
},
},
plugins: [
'~/plugins/nuxt-axios.js',
{ src: '~/plugins/nuxt-auth.js', mode: 'client' },
],
}

nuxt-auth.js是错误情况下的基本记录器

import $toast from '~/mixins/buefy-toast'
export default function ({ $auth }) {
$auth.onError((_name, error) => {
$toast.open({ message: error })
})
}

另一个重要部分是我的登录流程(在表单提交时触发(

export default {
methods: {
async authMe() {
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
}
}
// ...
}
}

在进行身份验证时,我们基本上不会在API上获取用户,而是提交凭据并验证它们,然后使用函数$auth.setUser手动设置标志。这是我处理的将loggedIn标志传递为true的唯一部分,剩下的配置只是项目配置
我们的JWT上也有一些refreshToken,但您可以完全忽略这个。

Axios配置文件基本上是设置我们的应用程序所需的标题。

auth中间件是@nuxt/auth模块本身的中间件,我不是自己写的。当使用target: 'static'生成时,这完全有效(cookie+vuex状态(。

此错误是由于节点版本的原因,您可以安装16.9.1版本并解决此错误。

在我的案例中,我的版本是18.14.2,它给了我/login重定向错误,因为在SSR模式下刷新页面时,服务器将$auth.loggerIn变量返回为false,并在我进入客户端部分时变为true。所以中间件总是发送登录重定向规则。

理论上,你应该在nuxtServerInit中添加一个部分来获取存储在该变量中的cookie,并将其添加到某个地方哈哈

但我真的不知道是否能做到