Reactjs令牌到期时间 [英] Reactjs Token expiration time

查看:125
本文介绍了Reactjs令牌到期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Reactjs登录创建单页Web.问题是如何以及在何处保存令牌到期时间.我是否需要保存在sessionStore中,但是当浏览器关闭时,所有数据都将被删除.本地商店?但是,数据将永远存在.或者我可以保存在localStore中,在每个事件中我都必须添加功能,以检查事件触发再次成功更新localstore时localStore的到期时间?但是代码看起来太可怕了……性能问题又如何呢?这种做法可以接受吗?

i making single page web with login with Reactjs. Problem is how and where to save token expire time. Do i need to save in sessionStore, but when browser closes all data will be deleted. Local Store? But then data will be forever. Or i can save in localStore and in every event i have to add function, that checks expire time from localStore, when event triggered successfully update localstore again? but code will look horrible... and how about performance issues? Is this approuche acceptible?

推荐答案

您是否使用Redux&& Redux重击了吗?

如果是这样,这就是我遵循的方法:

If so, here's the approach I followed:

  1. 用户登录后,我将访问权限和刷新令牌保留在商店中.
  2. 我正在使用 redux-persist 将令牌保留在localStorage中(有其他存储空间),以便在用户刷新/重新打开应用程序时保留它们.
  3. 具有一个中间件,该中间件在每个API请求之前检查访问令牌是否仍然有效.
  1. When the user logged in, I keep the access and refresh tokens in the Store.
  2. I'm using redux-persist to keep the tokens in the localStorage (there are other storage too), in order to persist them, when the user refreshes / reopen the app.
  3. Having a middleware, that checks if the access token is still valid before every one API request.
  1. 如果已过期,请尝试使用刷新令牌刷新访问令牌.
  2. 如果未过期,只需执行API请求即可.

  • 如果用户注销或两个令牌都到期,那么我将清除商店(也通过redux-persist清除localStorage).
  • 更多细节,对于上述流程,您可以签入原始答案(我从中得到启发): https://stackoverflow.com/a/36986329/4312466

    More details, for the above flow, you can check in the original answer (where from I took inspirations): https://stackoverflow.com/a/36986329/4312466

    如果您不使用任何状态管理库:

    可以遵循上述想法,但是除了拥有商店,中间件和使用redux-persist之外,您还可以:

    It's an option to follow the above idea, but instead of having a store, middleware, and using redux-persist, you can:

    1. 将令牌保留在localStore中.
    2. 在应用程序中创建一个层(类,函数或所需的任何层),该层将充当中间件.每次您要调用API时,都将首先调用此层,这将检查令牌是否有效:
    1. Keep the tokens in localStore.
    2. Create a layer (class, function or whatever you want) in your app, that will act as middleware. Every time you want to call the API, you will call this layer firstly, that will check if the token is valid:
    1. 如果是这样,则只有这样才能触发API请求.
    2. 如果令牌已过期,则该层将在尝试刷新令牌的同时将所有其他API请求保留在队列中.


    但是,如果您执行SPA并具有复杂的状态操作,建议您使用一些状态管理库.


    However, if you do SPA and have complex state operations, I recommend you to use some State management library.

    这篇关于Reactjs令牌到期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆