redux 局部刷新

by Sachin Kumar

由Sachin Kumar

如何使用Redux Observables和刷新令牌API获取新的访问令牌 (How to get a new access token using Redux observables and the refresh token API)

This article is about how I handled a 401 status code on an API response. I will show you how to get a new access token using the refresh token with Redux Observable in a React project.

本文是关于我如何处理API响应上的401状态代码。 我将向您展示如何使用Redux Observable的刷新令牌获取新的访问令牌 在一个React项目中

However before we begin, we should understand some of the prerequisite concepts that will help up understand the solution better. This is a general architectural solution to a common problem, so you don’t need to know Redux to read further. Let us begin!

但是,在开始之前,我们应该了解一些先决条件概念,这些概念将有助于更好地理解解决方案。 这是解决常见问题的通用架构解决方案,因此您无需了解Redux即可进一步阅读。 让我们开始吧!

访问令牌 (Access token)

Access Token is a credential that can be used by an application to access an API. When an access token expires, it throws 401 status code in error response.

访问令牌是一种凭证,应用程序可以使用它来访问API。 当访问令牌过期时,它将在错误响应中引发401状态代码。

The below flowchart shows, how an access token works with the server. — auth0.com

下面的流程图显示了访问令牌如何与服务器一起使用。 — auth0.com

This is how an auth service works when the user successfully logs in and retrieves an access token and refreshes the token on successful authentication.

当用户成功登录并检索访问令牌并在成功进行身份验证时刷新令牌时,身份验证服务将以这种方式工作。

刷新令牌 (Refresh Token)

A Refresh Token is a special kind of token that can be used to obtain a renewed access token — that allows accessing a protected resource — at any time. You can request new access tokens until the refresh token is blacklisted. Refresh tokens must be stored securely by an application because they essentially allow a user to remain authenticated forever. — auth0.com

刷新令牌是一种特殊的令牌,可用于随时获取更新的访问令牌(允许访问受保护的资源)。 您可以请求新的访问令牌,直到刷新令牌被列入黑名单。 刷新令牌必须由应用程序安全地存储,因为它们本质上允许用户永远保持身份验证。 — auth0.com

We need to get a new access token using that refresh token, then again hit the same API with the new access token. We want to do this without the user knowing that their session has expired or the API throwing an error.

我们需要使用该刷新令牌获取新的访问令牌,然后再次使用新的访问令牌访问相同的API。 我们希望在用户不知道自己的会话已过期或API引发错误的情况下执行此操作。

Let’s understand how the refresh token works with the server. We retrieve a new access token when the API throws a 401 status code.

让我们了解刷新令牌如何与服务器一起使用。 当API抛出401状态代码时,我们将获取一个新的访问令牌。

The refresh token API call receives a new access token from the auth server using the refresh token saved on the first authentication.

刷新令牌API调用使用保存在第一次身份验证中的刷新令牌从auth服务器接收新的访问令牌。

We can better understand this whole process via this simple flow chart.

通过这个简单的流程图,我们可以更好地理解整个过程。

可观察的 (Observables)

You can think of an observable as an array whose items arrive asynchronously over time. Observables help you manage asynchronous data, such as data coming from a backend service.

您可以将observable视为一个数组,其项随时间异步到达。 Observables帮助您管理异步数据 ,例如来自后端服务的数据。

In RxJS, this can become pretty complex when playing with observable streams. Don’t worry — we are going to simplify this with simple code chunks.

在RxJS中,当使用可观察的流播放时,这可能变得非常复杂。 不用担心-我们将通过简单的代码块来简化此过程。

Let’s start with a simple API call in redux-observable. This is what a simple function for a fetch API looks like :

让我们从redux-observable中的简单API调用开始。 这是获取API的简单功能,如下所示:

解 (Solution)

Now we are armed with the basic concepts. Let us see how we can handle a 401 (invalid_token or session expired) status code on an API response. We’ll also see how we can get the new access token using the refresh token in Redux Observable.

现在,我们掌握了基本概念。 让我们看看如何处理API响应中的401(invalid_token或会话已过期)状态代码。 我们还将看到如何使用Redux Observable中的刷新令牌来获取新的访问令牌。

We have to make two changes in the above function:

我们必须对以上功能进行两项更改:

  1. Wrap our API call in Observables.defer(). We want to get ahold of that function to call again when the new valid access token is received.将我们的API调用包装在Observables.defer()中。 我们希望让该函数在收到新的有效访问令牌后再次调用。
  2. When we get a 401 status in catch error. We need to make an API call to get the new access token. We use the refresh token stored in the first successful authentication.当我们在捕获错误中获得401状态时。 我们需要进行API调用以获取新的访问令牌。 我们使用存储在第一次成功身份验证中的刷新令牌。

Let’s see the differences between the two functions:

让我们看看两个函数之间的区别:

  1. The catch function always gives the source of the parent stream. We can use that to start the stream again which failed due to an invalid access token.

    catch函数始终提供父流的 。 我们可以使用它再次启动流,由于访问令牌无效而失败。

  2. Now start a new stream of events to listen for refresh token success events. We stop when the refresh token API fails (use takeUntil for this).现在开始一个新的事件流,以侦听刷新令牌成功事件。 当刷新令牌API失败时,我们将停止(为此使用takeUntil)。
  3. Now make sure you use the take operator to always get the first event of the stream. If you have multiple streams, your output stream can be compromised.

    现在,确保使用take运算符始终获取流的第一个事件。 如果您有多个流,则可能会损害您的输出流。

  4. If the new access token has been received, then use mergeMap to merge the source of the previous stream. We merge it again to the parent stream, and it will call the get data function with the new access token.如果已收到新的访问令牌,则使用mergeMap合并上一个流的源。 我们再次将其合并到父流,它将使用新的访问令牌调用get data函数。
  5. Now you might be wondering how merge is working. So, merge independently invokes and will start its own stream to fetch the new access token using the refresh token (check out the next function). When the refresh token success appears, it will get to step 2 and so on.

    现在您可能想知道合并是如何工作的。 因此,merge独立调用,并将使用刷新令牌(检查下一个功能)启动其自己的流以获取新的访问令牌。 当刷新令牌成功出现时,它将进入步骤2 ,依此类推。

We can use this approach to handle more special cases for different status code as well like 500, 403.

我们可以使用这种方法来处理针对不同状态代码(例如500、403)的更多特殊情况。

ProTip: make sure to check for infinite loop condition if the refresh token API gives a 401. You can maintain a counter on every refresh token call. If the number exceeds, stop the stream. Then do any error handling on it, for example showing a message that there was an error, and logout the user.

ProTip :如果刷新令牌API给出401,请确保检查无限循环条件。您可以在每次刷新令牌调用时维护一个计数器。 如果数量超过,请停止播放流。 然后对它进行任何错误处理,例如显示一条消息,指出存在错误,然后注销用户。

结论 (Conclusion)

We have implemented an invalid token handler using a refresh token API with Redux-observables in React. This approach can be used to handle other special API cases as well.

我们在React中使用带有Redux-observables的刷新令牌API实现了无效的令牌处理程序。 这种方法也可以用于处理其他特殊的API情况。

I hope you enjoyed the post, if you like it follow me on Twitter and Github for more JavaScript tips and articles. ?

我希望您喜欢这篇文章,如果您喜欢它,请在Twitter和Github上关注我,以获取更多JavaScript技巧和文章。

一些有用的资源 (Some helpful resources)

  1. https://redux-observable.js.org/

    https://redux-observable.js.org/

  2. https://rxjs-dev.firebaseapp.com/api

    https://rxjs-dev.firebaseapp.com/api

  3. https://rxjs-dev.firebaseapp.com/api/index/function/defer

    https://rxjs-dev.firebaseapp.com/api/index/function/defer

  4. https://rxjs-dev.firebaseapp.com/api/index/function/merge

    https://rxjs-dev.firebaseapp.com/api/index/function/merge

翻译自: https://www.freecodecamp.org/news/how-to-get-a-new-access-token-using-redux-observables-and-the-refresh-token-api-d38d875a8add/

redux 局部刷新

redux 局部刷新_如何使用Redux Observables和刷新令牌API获取新的访问令牌相关推荐

  1. hooks taro 下拉刷新_小程序自定义下拉刷新(Taro版)

    在考虑实现自定义的下拉刷新组件的时候,首先要明确,这个算是一种hack方案.并不是说自定义的有多么好,反而自定义的下拉刷新在android下会有细微的卡顿(我这种实现方式).所以尽量还是用小程序自带的 ...

  2. java 判断页面刷新_如何判断一个网页是刷新还是关闭的方法

    页面加载时只执行onload 页面关闭时只执行onunload 页面刷新时先执行onbeforeunload,然后onunload,最后onload.这样我们可以在onbeforeunload中加一个 ...

  3. js app缓存自动刷新_如何通过清除缓存来刷新App Store中的内容

    js app缓存自动刷新 Are you finding that you're not seeing new apps on the App Store, or that updates to ap ...

  4. 小程序下拉刷新_微信小程序下拉刷新

    下拉刷新是常用操作,微信已经集成好了(真机效果稍有瑕疵) 首先需要在.json文件启用下拉刷新 {"enablePullDownRefresh": true, } 然后在.js文件 ...

  5. unity text不能刷新_厦门泳池派对惊喜之Carta与Unity合作新单预告派对

    我们多久没有号召厦门的好朋友们见面了?也许几个月?也许半年以上?值得庆幸的是,在令人烦躁.焦虑的夏日,我们发现了有趣的清凉时刻.你最爱的泳池派对回来了.「Sunset Sessions」对于任何舞客来 ...

  6. 全球地区资料json 含中英文 经纬度_爬虫实战(三)使用百度API获取经纬度/地址...

    点击上方"蓝字"关注我们百度API获取经纬度/地址Mar 28, 2020 本期介绍给定地址/经纬度,使用百度API来获取经纬度/地址. 本文约3k字,预计阅读18分钟. 本次是第 ...

  7. html刷新css样式,让IE浏览器即时刷新CSS样式_HTML与CSS教程_电脑知识学习_培训之家...

    让IE浏览器即时刷新CSS样式为http://www.pxzj8.com整理发布,类型为HTML与CSS教程,本站还有更多关于html与css教程,css教程,html网页设计教程,css视频教程,c ...

  8. [Redux/Mobx] 举例说明怎么在redux中定义action?

    [Redux/Mobx] 举例说明怎么在redux中定义action? 利用actionCreator // 用户选择需要显示的subreddit export const SELECT_SUBRED ...

  9. redux reducer_如何通过约定创建Redux reducer

    redux reducer Discover Functional JavaScript was named one of the best new Functional Programming bo ...

最新文章

  1. 观点PK_倘若做不好AI,云服务商还能勇往直前吗?
  2. day3 集合、文件操作、函数、局部变量
  3. CSS布局之flex布局
  4. 网络硬盘与传统资源共享的不同
  5. Ubuntu12.10编译openwrt遇到的错误
  6. wps不能打印_excel小技巧:在手机上的文件的保存、分享、打印
  7. C语言学生成绩简单,C语言实现简单学生成绩管理系统.pdf
  8. 手机技巧:手机丢了记住这四步操作,让你的损失降到最低!
  9. [改善Java代码]非稳定排序推荐使用List
  10. html网页定位,HTML_定位网页元素(示例代码)
  11. gcc较高版本的一些编译警告收集
  12. 读书笔记 effective c++ Item 41 理解隐式接口和编译期多态
  13. bat导出远程oracle数据,windows 任务计划 实现oracle远程 数据库备份
  14. Android客户端获取服务器的json数据(二)
  15. 红外万能遥控器2.0,把家里的红外遥控器改成能用语音和手机app控制
  16. 关于程序员的996,我们谈谈历史和逻辑
  17. 计算机大赛鼓励语录,鼓励参加比赛的话
  18. DNA序列编码中Hairpin的定义和计算
  19. BigDecimal运算和比较大小
  20. html点击按钮跳出消息框

热门文章

  1. swift 和 oc中检测textfield是否输入数字
  2. XCode 导入头文件不提示解决
  3. UILayer的一些属性
  4. Django web框架
  5. 极速理解设计模式系列:11.单例模式(Singleton Pattern)
  6. 浅谈C/C++中的static和extern关键字
  7. ionic + cordova+angularJs 搭建的H5 App完整版总结
  8. 剑指offer青蛙跳台阶问题
  9. 实现数组字符串翻转的两种方法
  10. linux中的for命令