login - API 平台 + Nuxt - 会话管理
问题描述
我是 Nuxt 和 API 平台的新手。我已经创建了一个基本的服务器和客户端,并且正在尝试解决如何进行会话管理。
我可以纯粹在客户端登录,例如使用 Nuxt Auth0 支持。或者我可以滚动自己的登录。但这只是客户端。或者我可以在 Symfony 服务器上使用表单登录并从客户端发布到它,但这只是服务器端。
我想要的是 Nuxt 能够判断我是否登录到 Symfony。对于使用 API 平台的通用 Nuxt 应用程序,正确的方法是什么?中间件?服务器中间件?nuxtServerInit?
解决方案
我有一些有用的东西,所以我想我会在这里发帖,以防其他人提供一些指导。
基本思想是:
- 在 Nuxt 端,使用中间件在页面渲染的其余部分发生之前检查我们是否登录到服务器。
- 在 API 平台方面,按照此处设置 JWT 身份验证。这给了我们一个令牌,我们将在 API 请求上发送它来验证它们。
在 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')
})
}
我对此并不完全满意,我相信它可能会更好。但是沿着这些思路的东西看起来可以完成这项工作。
推荐阅读
- c - 链接 2 个源文件而不是使用头文件有什么意义?
- powershell - Word ExportAsFixedFormat
- arrays - 在 Golang 中添加 2 个数组类型
- string - 如何在 Golfscript 中为字符串添加单个反斜杠?
- node.js - 无法将 nodejs 部署到 azure
- reactjs - 将 `console.log` 添加到所有 `useEffect`
- go - Go 例程后关闭冗余 sql.Rows 对象的推荐方法
- python - 是否可以使用 requests 模块从 Reverso Context 获取带有单词翻译的例句?
- javascript - JS - 强制打印死键
- powershell - 按数字动态分组对象Powershell