发布于 2021-11-19 15:33:59
我有点困惑,首先你说API数据,另一个句子你说JSON页面..然而。如果您想保护一个页面,那么您可以创建一个中间件。
中间件/Auth.js
export default async function ({ store, $axios, redirect }) {
let valid = await $axios.$post('/api/checktoken')
if (!valid) {
redirect('/')
}
}您需要创建一个API来检查令牌。通常,您需要像Authentication: Bearer token...一样在头中放置令牌,但是我只需将令牌保存在cookie中即可。因为如果您向服务器发送HTTP请求,cookie将自动发送,因此我不需要做额外的工作。
下一步是访问某个页面并设置您的中间件auth。
page.vue
<script>
export default {
middleware: "auth"
}
</script>然而,如果您想保护一些后端路由,您可以这样做。再次创建一个中间件
async authenticate(req, res, next) {
let token = await cookieService.getTokenFromCookie(req)
if (!token) return errorService.resError(res, 400, 'Authorization failed')
let tokenValid = await tokenService.verifyToken(token)
if (!tokenValid)
return errorService.resError(res, 400, 'Authorization failed')
let decodedData = tokenService.decode(token)
if (!decodedData)
return errorService.resError(res, 400, 'Authorization failed')
res.locals.userId = decodedData.userId
res.locals.role = decodedData.role
next()
}在这种情况下,您基本上需要从cookie中读取令牌。(如果您不使用cookie,您将需要从头中读取它,为此,您应该创建一个从标头中读取令牌的函数)
检查令牌是否在那里。
验证令牌是否有效。
解码令牌,以便访问其中的数据。
现在,您还可以将数据放到res.locals中。其优点是,该数据的作用域为当前请求,您可以在下一个中间件/端点中访问它。
然后调用next()到下一个中间件/端点
function endpoint(req, res) {
let { userId, role } = res.locals
do something....
}所以路线看起来是这样的:
app.use("/some/api/point", authenticate, endpoint)好处是您可以将authenticate放入您想要保护的每一个API路由中。
https://stackoverflow.com/questions/70037012
复制相似问题