[英]Is there a limit to the depth of nested routes you can do in Nuxt.js?
[英]In Nuxt.js how do you restrict some routes only to clients with a valid JWT token?
在Nuxt.js 中,这是实现身份验证的一种方法:
我不明白的是如何让 Nuxt 后端意识到对于某些受保护的路由,它必须在提供页面 JSON 数据之前检查客户端的 JWT 令牌。 我的意思是,我可以在Nuxt的哪个地方实现这种验证?
好吧,我首先有点困惑,你说 API 数据另一个句子你说 JSON 页面.. 但是。 如果要保护 PAGE,则创建中间件
中间件/auth.js
export default async function ({ store, $axios, redirect }) {
let valid = await $axios.$post('/api/checktoken')
if (!valid) {
redirect('/')
}
}
您需要创建一个 API 来检查令牌。 通常您需要将令牌放入您的 header 中,例如Authentication: Bearer token...
但是我只是将令牌保存在 cookie 中。 因为如果您向服务器发送 HTTP 请求,cookies 会自动发送,所以我不需要做一些额外的工作。
下一步是将 go 设置到某个页面并设置中间件身份验证。
页面.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 中读取令牌。 (如果你不使用 cookies 你需要从你的 header 中读取它,所以为此你应该创建一个 function 来读取你的令牌)
检查令牌是否在那里。
验证令牌是否有效。
解码令牌,以便您可以访问其中的数据
现在您还可以将数据放入您的res.locals
中。 优点是此数据的范围仅限于当前请求,您可以在下一个中间件/端点中访问它。
然后你调用next()
进入下一个中间件/端点
function endpoint(req, res) {
let { userId, role } = res.locals
do something....
}
所以路线看起来像这样:
app.use("/some/api/point", authenticate, endpoint)
好处是您可以在要保护的每个 API 路由中添加authenticate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.