设置“isAuthenticated”是不好的做法吗?本地存储中的标志?
这更多是一般性的前端问题,但就上下文而言,我使用的是 Vue 3 和 vue-router。
我正在构建使用 Vue 3 进行身份验证的功能。因为我没有使用 Vuex,所以我找不到从实例化路由器的文件中访问状态的方法。所以我想也许我应该将一个名为 isAuthenticated
的标志粘贴到 LocalStorage 中。
当用户登录时,isAuthenticated
被设置为 true,然后路由器从中读取以验证后续重定向。这与在 LocalStorage 中存储令牌非常不同 – 我将令牌存储在 httpOnly cookie 中。
对于那些了解 Vue3/Vue-router 的人来说,它看起来像这样:
Router.beforeEach(async (to, from) => {
// localStorage.isAuthenticated = false
const isAuthenticated = localStorage.isAuthenticated;
if (
// make sure the user is authenticated
isAuthenticated !== 'true' &&
to.meta.requiresAuth &&
// Avoid an infinite redirect
to.path !== '/login'
) {
// redirect the user to the login page
return '/login'
}
})
如果有人破解了这个并将标志更改为 true
,那也没什么大不了的;我的后端将拒绝任何没有正确 JWT 令牌的 API 调用。
但这是不好的做法吗?感觉有点脆弱,我希望编写一个强大且安全的应用程序。
This is more of general frontend question, but for context, I'm using Vue 3 and vue-router.
I'm constructing functionality for authentication with Vue 3. Because I'm not using Vuex, I couldn't find a way to access state from the file where the router is instantiated. So I thought maybe I'd stick a flag called isAuthenticated
into LocalStorage.
When the user logs in, isAuthenticated
gets set to true, and then the router reads from this to validate subsequent redirects. This is very different from storing a token in LocalStorage – I store my tokens in httpOnly cookies.
For those that know Vue3/Vue-router, it looks like this:
Router.beforeEach(async (to, from) => {
// localStorage.isAuthenticated = false
const isAuthenticated = localStorage.isAuthenticated;
if (
// make sure the user is authenticated
isAuthenticated !== 'true' &&
to.meta.requiresAuth &&
// Avoid an infinite redirect
to.path !== '/login'
) {
// redirect the user to the login page
return '/login'
}
})
It would be no big deal if someone hacked this and changed the flag to true
; my backend will reject any API call that doesn't have the right JWT token.
But is this bad practice? It feels a little flimsy, and I'm looking to write a robust and secure app.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论