passport身份验证_了解如何使用Passport.js处理Node身份验证

passport身份验证

by Antonio Erdeljac

通过安东尼奥·埃尔德雅克

了解如何使用Passport.js处理Node身份验证 (Learn how to handle authentication with Node using Passport.js)

Support me by reading it from its original source: ORIGINAL SOURCE

通过阅读原始来源为我提供支持: 原始来源

In this article you will learn how to handle authentication for your Node server using Passport.js. This article does not cover Frontend authentication. Use this to configure your Backend authentication (Generate token for each user & protect routes).

在本文中,您将学习如何使用Passport.js处理节点服务器的身份验证 本文不介绍前端身份验证。 使用此配置您的后端身份验证 (为每个用户生成令牌并保护路由)。

Keep in mind that if you get stuck on any step, you can refer to this GitHub repo.

请记住, 如果您遇到任何困难,可以参考此GitHub存储库

在本文中,我将教您以下内容: (In this article I will teach you the following:)

  • Handling protected routes

    处理受保护的路线
  • Handling JWT tokens

    处理JWT令牌
  • Handling unauthorised responses

    处理未经授权的回复
  • Creating a basic API

    创建一个基本的API
  • Creating models & schemas

    创建模型和模式

介绍 (Introduction)

什么是Passport.js? (What is Passport.js?)

Passport is authentication middleware for Node.js. As it’s extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies supports authentication using a username and password, Facebook, Twitter, and more. Find out more about Passport here.

Passport是Node.js的身份验证中间件。 由于Passport非常灵活且模块化,因此可以毫不费力地将其放入任何基于Express的Web应用程序中。 一套全面策略支持认证的使用用户名和密码 , Facebook的 , Twitter的 ,和更多 。 在此处了解有关Passport的更多信息。

讲解 (Tutorial)

从头开始创建我们的节点服务器 (Creating our node server from scratch)

Create a new directory with this “app.js” file inside:

使用此“ app.js”创建一个新目录 里面的文件:

We will install nodemon for easier development.

我们将安装nodemon以便于开发。

and then we will run our “app.js” with it.

然后我们将使用它运行“​​ app.js”。

$ nodemon app.js

创建用户模型 (Creating the user model)

Create a new folder called “models”, and create the “Users.js” file inside that folder. This is where we will define our “UsersSchema”. We are going to use JWT and Crypto to generate hash and salt from the received password string. This will later be used to validate the user.

创建一个名为“模型”的新文件夹, 并在该文件夹中创建“ Users.js”文件。 这是我们定义“ UsersSchema”的地方。 我们将使用JWTCrypto从接收到的password字符串生成hashsalt 。 稍后将使用它来验证用户。

Let’s add our newly created model to “app.js”.

让我们将新创建的模型添加到“ app.js”中。

Add the following line to your “app.js” file after configuring Mongoose:

配置Mongoose之后,将以下行添加到您的“ app.js”文件中:

require('./models/Users');

配置护照 (Configure Passport)

Create a new folder “config” with the “passport.js” file inside it:

创建一个新文件夹“ config”,其中包含“ passport.js”文件:

In this file, we use the method validatePassword that we defined in the User model . Based on the result, we return a different output from Passport’s LocalStrategy.

在此文件中,我们使用在User model定义的validatePassword方法 。 根据结果​​,我们从Passport的LocalStrategy返回不同的输出。

Let’s connect “passport.js” to our “app.js” file. Add the following line below all models:

让我们将“ passport.js”连接到我们的“ app.js”文件。 在所有 models 下面添加以下行:

require('./config/passport');

路由和身份验证选项 (Routes and authentication options)

Create a new folder called “routes” with the file “auth.js” inside it.

创建一个名为“ routes”的新文件夹,其中包含文件“ auth.js”。

In this file we use the function getTokenFromHeaders to get a JWT token that will be sent from the client side in the request’s headers. We also create an auth object with optional and required properties. We will use these later in our routes.

在此文件中,我们使用功能getTokenFromHeaders来获取JWT令牌 ,该令牌将从客户端请求标头中发送 。 我们还将创建一个具有optionalrequired属性的auth对象。 我们将在以后的路线中使用它们。

In the same “routes” folder create an “index.js” file:

在相同的“ routes”文件夹中创建一个“ index.js”文件:

We now need an “api” folder inside the “routes” folder, with another “index.js” file inside it.

现在,我们在“ routes”文件夹中需要一个“ api”文件夹,其中还有另一个“ index.js”文件。

Now, let’s create the “users.js” file that we require in “api/index.js”.

现在,让我们在“ api / index.js”中创建所需的“ users.js”文件。

First, we are going to create an optional auth route ‘/’ which will be used for new model creation (register).

首先,我们将创建一个可选的身份验证路由'/' ,该路由将用于新模型的创建(注册)。

router.post('/', auth.optional, (req, res, next) ...

After that, we are going to create another optional auth route ‘/login’ . This will be used to activate our passport configuration and validate a received password with email.

之后,我们将创建另一个可选的身份验证路由'/login' 。 这将用于激活我们的护照配置并通过电子邮件验证收到的密码。

router.post('/login', auth.optional, (req, res, next) ...

Lastly, we will create a required auth route, which will be used to return the currently logged in user. Only logged in users (users that have their token successfully sent through request’s headers) have access to this route.

最后,我们将创建所需的身份验证路由,该路由将用于返回当前登录的用户。 只有登录的用户(通过请求的标头成功发送了令牌的用户)可以访问此路由。

router.get('/current', auth.required, (req, res, next) ...

Let’s add our “routes” folder to “app.js”. Add the following line below our passport require:

让我们将“ routes”文件夹添加到“ app.js”。 在我们的护照 require 下方添加以下行:

app.use(require('./routes'));

路线测试 (Route testing)

I will be using Postman to send requests to our server.

我将使用邮递员 发送请求到我们的服务器。

Our server accepts the following body:

我们的服务器接受以下主体:

{"user": {"email": String,"password": String}
}

创建POST请求以创建用户 (Creating a POST request to create a user)

Test body:

测试体:

Response:

响应:

{"user": {"_id": "5b0f38772c46910f16a058c5","email": "erdeljac.antonio@gmail.com","token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVyZGVsamFjLmFudG9uaW9AZ21haWwuY29tIiwiaWQiOiI1YjBmMzg3NzJjNDY5MTBmMTZhMDU4YzUiLCJleHAiOjE1MzI5MDgxNTEsImlhdCI6MTUyNzcyNDE1MX0.4TWc1TzY6zToHx_O1Dl2I9Hf9krFTqPkNLHI5U9rn8c"}
}

We will now use this token and add it to our “Headers” in Postman’s configuration.

现在,我们将使用此令牌并将其添加到Postman配置中的“标题”中。

And now let’s test our auth only route.

现在,让我们测试仅验证身份的路由。

创建一个GET请求以返回当前登录的用户 (Creating a GET request to return the currently logged in user)

Request URL:

要求网址:

GET http://localhost:8000/api/users/current

Response:

响应:

{"user": {"_id": "5b0f38772c46910f16a058c5","email": "erdeljac.antonio@gmail.com","token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVyZGVsamFjLmFudG9uaW9AZ21haWwuY29tIiwiaWQiOiI1YjBmMzg3NzJjNDY5MTBmMTZhMDU4YzUiLCJleHAiOjE1MzI5MDgzMTgsImlhdCI6MTUyNzcyNDMxOH0.5UnA2mpS-_puPwwxZEb4VxRGFHX6qJ_Fn3pytgGaJT0"}
}

Let’s try to do it without token in “Headers”.

让我们尝试在“标题”中不带令牌的情况下进行操作

Response:

响应:

结束 (The end)

Thank you for going through this tutorial. If you notice any errors please report them to me. If you got stuck on any step, please refer to this GitHub repo.

感谢您阅读本教程。 如果您发现任何错误,请向我报告。 如果您在任何步骤上都遇到困难,请参阅此GitHub存储库 。

You can contact me through:

您可以通过以下方式与我联系:

  • erdeljac DOT antonio AT gmail.com

    erdeljac DOT antonio AT gmail.com
  • Linkedin

    领英

Check out my app SwipeFeed.

查看我的应用程序SwipeFeed 。

翻译自: https://www.freecodecamp.org/news/learn-how-to-handle-authentication-with-node-using-passport-js-4a56ed18e81e/

passport身份验证

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394125.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode1448. 统计二叉树中好节点的数目(dfs)

给你一棵根为 root 的二叉树,请你返回二叉树中好节点的数目。 「好节点」X 定义为:从根到该节点 X 所经过的节点中,没有任何节点的值大于 X 的值。 代码 /*** Definition for a binary tree node.* public class TreeNode {* int val;…

I/O模型系列之四:两种高性能IO设计模式 Reactor 和 Proactor

不同的操作系统实现的io策略可能不一样,即使是同一个操作系统也可能存在多重io策略,常见如linux上的select,poll,epoll,面对这么多不同类型的io接口,这里需要一层抽象api来完成,所以就演变出来两…

python中序列类型和数组之间的区别_「Python」序列构成的数组

一、Python 标准库的序列类型分为:容器序列:能够存放不同类型数据的序列(list、tuple、collections.deque)。扁平序列:只能容纳一种类型的数据(str、bytes、bytearray 和 array.array)。其中,容器序列存放的是它们所包含的任意类型…

如何使用EF Core在Blazor中创建级联的DropDownList

介绍 (Introduction) In this article, we are going to create a cascading dropdown list in Blazor using Entity Framework Core database first approach. We will create two dropdown lists — Country and City. Upon selecting the value from the country dropdown, …

gcc/g++命令

参考:http://www.cnblogs.com/cryinstall/archive/2011/09/27/2280824.html 注意:gcc和g是linux系统下的编程常用指令,C语言文件用gcc,cpp文件用g。 1.预处理 g -E filename.cpp > filename.i 功能:输出预处理后的…

计算机存储

位(bit):一个数字0或一个数字1,代表一位 字节(Byte):每逢8位是一个字节,是数据存储的最小单位 1Byte 8 bit 平时所说的网速: 100Mbps实际上是以位(b&#xf…

leetcode113. 路径总和 II(dfs)

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。说明: 叶子节点是指没有子节点的节点。示例: 给定如下二叉树,以及目标和 sum 22,5/ \4 8/ / \11 13 4/ \ / \7 2 5 1 返回:[[5,4,11,…

java forward 修改请求参数_聊聊springboot session timeout参数设置

序本文主要介绍下spring boot中对session timeout参数值的设置过程。ServerPropertiesspring-boot-autoconfigure-1.5.8.RELEASE-sources.jar!/org/springframework/boot/autoconfigure/web/ServerProperties.javaOverridepublic void customize(ConfigurableEmbeddedServletCo…

javascript控制台_如何使用JavaScript控制台改善工作流程

javascript控制台by Riccardo Canella里卡多卡内拉(Riccardo Canella) 如何使用JavaScript控制台改善工作流程 (How you can improve your workflow using the JavaScript console) As a web developer, you know very well the need to debug your code. We often use extern…

appium===setup/setupclass的区别,以及@classmathod的使用方法

一、装饰器 1.用setUp与setUpClass区别 setup():每个测试case运行前运行 teardown():每个测试case运行完后执行 setUpClass():必须使用classmethod 装饰器,所有case运行前只运行一次 tearDownClass():必须使用classmethod装饰器,所有case运行完后只运行一次 2.是修饰符&#xf…

cache failed module status_Flutter混编之路——iOS踩坑记录

一、运行Xcode编译或者flutter run/build 过程中报错:"x86_64" is not an allowed value for option "ios-arch".解决方案在Debug.xcconfig中指定 “FLUTTER_BUILD_MODEdebug”,Release.xcconfig中指定“FLUTTER_BUILD_MODErelease”…

【最短路径Floyd算法详解推导过程】看完这篇,你还能不懂Floyd算法?还不会?...

简介 Floyd-Warshall算法(Floyd-Warshall algorithm),是一种利用动态规划的思想寻找给定的加权图中多源点之间最短路径的算法,与Dijkstra算法类似。该算法名称以创始人之一、1978年图灵奖获得者、斯坦福大学计算机科学系教授罗伯特…

java object类的常用子类_Java中Object类常用的12个方法,你用过几个?

前言Java 中的 Object 方法在面试中是一个非常高频的点,毕竟 Object 是所有类的“老祖宗”。Java 中所有的类都有一个共同的祖先 Object 类,子类都会继承所有 Object 类中的 public 方法。先看下 Object 的类结构(快捷键:alt7):1.…

leetcode面试题 04.12. 求和路径(dfs)

给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子…

javaweb学习总结(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册

一、ServletJSPJavaBean开发模式(MVC)介绍 ServletJSPJavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据。 ServletJSPJavaBean模式程序各个模块之间层次清晰&…

2018黄河奖设计大赛获奖_宣布我们的freeCodeCamp 2018杰出贡献者奖获奖者

2018黄河奖设计大赛获奖by Quincy Larson昆西拉尔森(Quincy Larson) 宣布我们的freeCodeCamp 2018杰出贡献者奖获奖者 (Announcing Our freeCodeCamp 2018 Top Contributor Award Winners) Over the past 3 years, freeCodeCamp.org has grown from a small open source proje…

Log4j配置详解

来自: http://www.blogjava.net/zJun/archive/2006/06/28/55511.html Log4J的配置文件(Configuration File)就是用来设置记录器的级别、存放器和布局的,它可接keyvalue格式的设置或xml格式的设置信息。通过配置,可以创建出Log4J的运行环境。1. 配置文件 …

cors数据类型_如何根据RTK的差分格式选择千寻cors账号的源节点进行设置?

千寻cors账号的设置中源节点是根据使用的品牌RTK是为双星仪器还是三星仪器选择,但问题就在于我们看到的RTK的技术参数中一般很少见到标注仪器的卫星系统,更多的是差分格式。其实千寻cors账号的源节点也可以根据RTK的差分格式进行选择,不过这两…

java swing 串口_ComTest 接收串口数据,并显示在文本框内,通过JavaSwing实现 Develop 265万源代码下载- www.pudn.com...

文件名称: ComTest下载 收藏√ [5 4 3 2 1 ]开发工具: Java文件大小: 3157 KB上传时间: 2016-09-21下载次数: 0提 供 者: 韩坤详细说明:接收串口数据,并显示在文本框内,通过JavaSwing实现-Receive serial data, and displayed in the t…

leetcode329. 矩阵中的最长递增路径(dfs)

给定一个整数矩阵,找出最长递增路径的长度。对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。示例 1:输入: nums [[9,9,4],[6,6,8…