drt*_*tob 6 javascript vue.js nuxt.js
我有一个使用 @nuxt/auth 设置的 Nuxt 应用程序。每当刷新页面时,用户总是会被重定向到登录页面。我猜想 Nuxt 应用程序的服务器端未登录,而客户端已登录。JWT 访问令牌是从 Express API 获取的。请有人帮我解决这个问题吗?这是我的 nuxt.config.js
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,
},
},
},
},
},
Run Code Online (Sandbox Code Playgroud)
还有我的仪表板.vue
export default {
middleware: ['auth'],
};
Run Code Online (Sandbox Code Playgroud)
这是我的工作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' },
],
}
Run Code Online (Sandbox Code Playgroud)
nuxt-auth.js是发生错误时的基本记录器
import $toast from '~/mixins/buefy-toast'
export default function ({ $auth }) {
$auth.onError((_name, error) => {
$toast.open({ message: error })
})
}
Run Code Online (Sandbox Code Playgroud)
另一个重要部分是我的登录流程(在表单提交时触发)
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,
})
}
}
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
在进行身份验证时,我们基本上不会让用户使用 API,而是提交凭据并验证它们,然后使用函数手动设置标志$auth.setUser。这是我处理将标志传递为 true 的唯一部分loggedIn,其余配置只是项目配置。
我们的 JWT 上也有一些refreshToken,但您可以完全忽略这一点。
Axios 配置文件基本上是设置我们应用程序所需的标头。
中间件auth是模块本身附带的@nuxt/auth,不是我自己编写的。当使用 生成时,这是完全有效的(cookies + vuex 状态)target: 'static'。
| 归档时间: |
|
| 查看次数: |
7883 次 |
| 最近记录: |