当前位置: 首页 > 编程日记 > 正文

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

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 局部刷新

相关文章:

九宫格抽奖转盘源码分析

效果如上图所示&#xff0c;下面对其实现代码进行分析&#xff0c;看能不能破解其抽奖规则。需要引入jquery-1.8.3.min.js和images/9张图片。 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-tra…

关于使用strtok的一个小问题

今天在弄一下啊小小程序的时候。报错&#xff0c;出现了问题。先看代码 int main(int argc, char* argv[]) {char *filename "interface_ipset_1_1.json";char* split1 "_";char* split2 ".";char splitfile1[4][NAME_MAX];sagent_string_sp…

微信小程序发送模板消息,php发送模板消息

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 formId 在安卓系统是纯数字&#xff0c;在IOS系统是一串加密字符&#xff0c;如图&#xff1a; 发送模板消息&#xff08;服务通知&#xff09;效果图&#xff1a; 前端 wxml <form bindsubmit"…

使用TypeScript映射和条件类型使React组件更出色

by Deepu K Sasidharan通过Deepu K Sasidharan 使用TypeScript映射和条件类型使React组件更出色 (Make your React components great with TypeScript mapped and conditional types) You’ve probably heard about TypeScript. You may have heard someone claiming how grea…

2017年6月16号课堂笔记

2017年6月16号 星期五 空气质量&#xff1a;中度污染~轻度污染 内容&#xff1a;jQuery&#xff1a;remove&#xff0c;bind&#xff0c;attr&#xff0c;on和live&#xff0c;同辈和父辈节点的操作&#xff0c; keyup/keypress/keydown,focus-blur应用&#xff0c;表单事件/键…

大宗商品(Bulk Stock)交易

大宗商品&#xff08;Bulk Stock&#xff09;是指可进入流通领域&#xff0c;但非零售环节&#xff0c;具有商品属性用于工农业生产与消费使用的大批量买卖的物质商品。在金融投资市场&#xff0c;大宗商品指同质化. 可交易. 被广泛作为工业基础原材料的商品大宗商品电子交易主…

【Ant Design Pro 二】 创建页面,组件,并在页面调用

开发交流qq群 173683895 路由里面的参数作用介绍: {path: "/a_nowdayserver/nowdayserver", //随便取名,显示在访问路径url中,如果是子路由,需要和父路径匹配icon: "file", //菜单栏显示的图标name: "你好", //菜单栏显示的标题component…

安卓收取费用_作为自由职业者应收取的费用:以价值为基础的定价是否能达到炒作的目的?...

安卓收取费用by Benek Lisefski由Benek Lisefski 作为自由职业者应收取的费用&#xff1a;以价值为基础的定价是否能达到炒作的目的&#xff1f; (What to charge as a freelancer: does value-based pricing live up to the hype?) 定价很难。 (Pricing is hard.) Even afte…

Java笔记(25):设计模式概述

1、设计模式的概述和分类 设计模式&#xff1a; 经验的总结。 A:创建型 创建对象 B:结构型 对象的组成 C:行为型 对象的功能创建型模式&#xff1a;1)简单工厂模式 2)工厂方法模式 3)设计模式 2、简单工厂模式概述和使用 1 package cn.itcast_01; 2 3 public abstract class A…

Ant Design Pro 使用图表 charts bizcharts

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 淌了一下午坑,都是辛酸泪 总结:首先要知道, 它不能直接使用 charts ,需要安装 bizcharts 插件,然后导入 bizcharts 中的 charts; 点击跳转到 bizcharts 官方文档,建议看完整个流程再跳转 首先,…

【剑指offer 面试题47】不用加减乘除做加法

思路&#xff1a; 利用位运算 C&#xff1a; 1 #include <iostream>2 using namespace std;3 4 int main()5 {6 int a 11, b 17;7 int sum, carry;8 do9 { 10 sum a ^ b; 11 carry (a & b) << 1; 12 a sum; 13 …

travis-ci自动部署_如何使用Travis CI部署(几乎)零恐惧的Cloud Foundry应用

travis-ci自动部署by Robin Bobbitt罗宾波比(Robin Bobbitt) 如何使用Travis CI部署(几乎)零恐惧的Cloud Foundry应用 (How to deploy your Cloud Foundry app with (almost) zero fear using Travis CI) Application deployments to the cloud should be painless. We should…

Activiti 规则任务(businessRuleTask)

Activiti 规则任务&#xff08;businessRuleTask&#xff09; 作者&#xff1a;邓家海 目前国内研究Activiti规则任务businessRuleTask&#xff09;的文章在网上应该不超出3篇 小觑夜漫酒作伴&#xff0c;破晓黎明当笑言 前言&#xff1a; 最近一直在研究Activiti工作流的自动化…

10年工作经验老程序员推荐的7个开发类工具

做.NET软件工作已经10年了&#xff0c;从程序员做到高级程序员&#xff0c;再到技术主管&#xff0c;技术总监。见证了Visual Studio .NET 2003,Visul Studio 2005, Visual Studio Team System 2008, Visual Studio 2010 Ultimate,Visual Studio 2013一系列近5个版本的变化与亲…

PHP SSL certificate: unable to get local issuer certificate的解决办法

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 当本地curl需要访问https时&#xff0c;出现SSL certificate: unable to get local issuer certificate错误信息 解决办法&#xff1a; 到http://curl.haxx.se/ca/cacert.pem下载pem文件&#xff0c;并…

辞职前为什么挣扎_当您感到自己像开发人员一样挣扎时,为什么学得最多

辞职前为什么挣扎by Walt Schlender由Walt Schlender 当您感到自己像开发人员一样挣扎时&#xff0c;为什么学得最多 (Why you learn the most when you feel like you’re struggling as a developer) The times when I have made the greatest leaps in my development skil…

Hadoop学习之Mapreduce执行过程详解

一、MapReduce执行过程 MapReduce运行时&#xff0c;首先通过Map读取HDFS中的数据&#xff0c;然后经过拆分&#xff0c;将每个文件中的每行数据分拆成键值对&#xff0c;最后输出作为Reduce的输入&#xff0c;大体执行流程如下图所示&#xff1a; 整个流程图具体来说&#xff…

汇编试验十五:安装新的int 9中断例程

安装新的int 9中断例程&#xff08;按A键后显示满屏幕的A&#xff09; int 9 是外中断&#xff0c;同样&#xff0c;程序编写还是和其他中断例程类似&#xff0c;安装&#xff08;复制&#xff09;&#xff0c;调用&#xff1b; 不同点是在于&#xff0c;他要从端口读取数据60h…

php判断前端传的多个字段与数据库匹配

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码 <?phpheader("Content-Type:text/html;charsetutf8"); header("Access-Control-Allow-Origin: *"); //解决跨域header(Access-Control-Allow-Methods:POST);// 响应类型 …

javascript编写_用JavaScript深入探讨:为什么对编写好的代码至关重要。

javascript编写Using simple terminology and a real world example, this post explains what this is and why it is useful.这篇文章使用简单的术语和一个真实的例子&#xff0c;解释了this是什么以及为什么有用。 这是给你的吗 (Is this for you) I have noticed that man…

peak num

class Solution {public: int findPeakElement(vector<int>& nums) { int i0; int nnums.size(); while(i<n){ if(i0){ //处理第一位 if(nums[1] < nums[0]) return 0; else { …

用Eclipse的snippets功能实现代码重用

snippets功能实现代码重用 Snippets 代码片段是Eclipse的一个插件。 很多时候可以通过这个功能&#xff0c;重复使用常用的代码片段&#xff0c;加快开发效率。 创建一个代码段的步骤&#xff1a; 在Eclipse的editor中选中一块代码段&#xff0c;右键点击【Add to Snippets…

JS删除选中的数组

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 js // 删除数组deleteArr: function (e) {let middlearr [{a:1},{b:2}];//全部数组let items [{a:1}];//选中的数组for (var i 0; i < items.length; i) {for (var j 0; j < middlearr.lengt…

Git合并和变基简介:它们是什么,以及如何使用它们

by Vali Shah通过瓦利沙阿 Git合并和Git变基简介&#xff1a;它们做什么以及何时使用它们 (An Introduction to Git Merge and Git Rebase: What They Do and When to Use Them) As a Developer, many of us have to choose between Merge and Rebase. With all the reference…

[转]单点登录原理与简单实现

一、单系统登录机制 1、http无状态协议 web应用采用browser/server架构&#xff0c;http作为通信协议。http是无状态协议&#xff0c;浏览器的每一次请求&#xff0c;服务器会独立处理&#xff0c;不与之前或之后的请求产生关联&#xff0c;这个过程用下图说明&#xff0c;三次…

[JAVA] DUMP

jmap -dump:live,formatb,fileD:\heap.bin 31563156是PID转载于:https://www.cnblogs.com/MasterMonkInTemple/p/4655547.html

ThinkPHP 5.0 入门教程 一:安装ThinkPHP并在Web浏览器访问

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 严格来说&#xff0c;ThinkPHP无需安装过程&#xff0c;这里所说的安装其实就是把ThinkPHP框架放入WEB运行环境&#xff08;前提是你的WEB运行环境已经OK&#xff09; 下面我们开始安装ThinkPHP的运行环…

以太坊区块链同步_以太坊69:如何在10分钟内建立完全同步的区块链节点

以太坊区块链同步by Lukas Lukac卢卡斯卢卡奇(Lukas Lukac) Ethereu M 69&#xff1a;如何在10分钟内建立完全同步的区块链节点 (Ethereum 69: how to set up a fully synced blockchain node in 10 mins) Welcome in the first article of our new go-ethereum series!欢迎来…

微信小程序客服实现自动回复图文消息链接,点击去关注公众号

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 用户打开客服消息&#xff0c;发送任意消息自动回复图文链接&#xff0c;达到关注公众号的目的。 先看效果&#xff1a; 打开芝麻小客服的后台&#xff0c;选择一键接入小程序智能客服 点击跳转 1.授权…

HtmlUnit、httpclient、jsoup爬取网页信息并解析

转载&#xff1a;http://tianxingzhe.blog.51cto.com/3390077/1755511转载于:https://www.cnblogs.com/puhongtao/p/7063563.html