我是Nuxt和API平台的新手。我已经创建了一个基本的服务器和客户端,我正在尝试研究如何进行会话管理。
我可以纯粹在客户端登录,例如使用Nuxt Auth0支持。或者我可以滚动我自己的登录。但那只是客户端。或者我可以在Symfony服务器上使用表单登录并从客户端发布到它,但这只是服务器端。
我想要的是Nuxt能够判断我是否登录到Symfony。使用API平台为通用Nuxt应用程序执行此操作的正确方法是什么?中间件?服务器中间件? nuxtServerInit?
我有一些有用的东西,所以我想我会回到这里,以防其他人有一些指示。
基本思路是:
在Nuxt客户端中,您需要一个处理登录状态的商店。这是我目前的WIP版本(所以我没有声称它的代码很棒):
import axios from 'axios'
export default function({ store, redirect }) {
store.commit('security/AUTHENTICATING')
// Add token header if we have it.
const token = store.state.security.token
if (token) {
axios.defaults.headers.common.Authorization = 'Bearer ' + token.toString()
} else {
axios.defaults.headers.common.Authorization = null
}
// Now make an API call to see if we're logged in.
return axios
.get(process.env.API + '/locations')
.then(response => {
// We're logged in. No need to save the token - it's already in the store.
store.commit('security/AUTHENTICATING_SUCCESS', null)
})
.catch(() => {
// We're not logged in.
if (store.state.security.isAuthenticated) {
// ...but we thought we were. Correct our misapprehension.
store.commit('security/LOGOUT')
}
// Ask them to log in.
return redirect('/login')
})
}
然后设置一些中间件:
import axios from 'axios'
export default function({ store, redirect }) {
store.commit('security/AUTHENTICATING')
// Add token header if we have it.
const token = store.state.security.token
if (token) {
axios.defaults.headers.common.Authorization = 'Bearer ' + token.toString()
} else {
axios.defaults.headers.common.Authorization = null
}
// Now make an API call to see if we're logged in.
return axios
.get(process.env.API + '/locations')
.then(response => {
// We're logged in. No need to save the token - it's already in the store.
store.commit('security/AUTHENTICATING_SUCCESS', null)
})
.catch(() => {
// We're not logged in.
if (store.state.security.isAuthenticated) {
// ...but we thought we were. Correct our misapprehension.
store.commit('security/LOGOUT')
}
// Ask them to log in.
return redirect('/login')
})
}
我对此并不完全满意,我相信它会更好。但是,沿着这些方向看起来它看起来会起作用。