如何检查JWT的有效性以设置更新
我正在使用React和JWT +刷新令牌。当我的用户登录时,我将在LocalStorage设置令牌和Refresh_token。
现在,我将令牌设置为5s的有效性,以使我的逻辑刷新令牌。
我的问题是,一旦我的用户登录,而令牌和刷新令牌存储在本地存储中,我该如何检查每个重新启动或重新渲染React的有效性?
我应该在每个页面上打个API吗?
这是我的loggin函数:
// Login user
const login = async (userData) => {
let datas;
await axios.post('/authentication_token', userData)
.then((response) => {
localStorage.setItem('user', JSON.stringify(response.data))
axios.defaults.headers.common['Autorization'] = `Bearer ${response.data.token}`
datas = response.data
})
return datas
}
I'm using React and JWT + refresh token. When my user log in, I set in localStorage the token and refresh_token.
Now, I set up my token to 5s validity to make my logic for refresh token.
My question is, once my user is logged in, and the token and refresh token are stored in Local Storage, how can I check the validity on each reload or re-render of react ?
Am i supposed to make an API call on every page ?
Here is my loggin function :
// Login user
const login = async (userData) => {
let datas;
await axios.post('/authentication_token', userData)
.then((response) => {
localStorage.setItem('user', JSON.stringify(response.data))
axios.defaults.headers.common['Autorization'] = `Bearer ${response.data.token}`
datas = response.data
})
return datas
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要
刷新API
在app.js
中调用,并使用setInterval()
每5秒调用您的刷新令牌API,然后刷新刷新令牌将更新。取而代之的是,您应该检查令牌的准确性,也许如果您的令牌到期您的API到期,则将您的401状态代码抛出401个状态代码,并且您将被登录。假设这是您的
app.js
You need to
refresh API
call inApp.js
and usesetInterval()
every 5 seconds to call your refresh token API, and your refresh token will be updated. Instead you should check the accuracy of the token, maybe if your token expires your API throw you 401 status code and you will be logged out.let say this is your
App.js