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.comerdeljac 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身份验证

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

  1. node oauth2验证_如何设置和使用护照OAuth Facebook身份验证(第2部分)| Node.js

    node oauth2验证 In my last article (How to set up and use passport OAuth Facebook Authentication (Sect ...

  2. node oauth2验证_如何设置和使用护照OAuth Facebook身份验证(第1部分)| Node.js

    node oauth2验证 In my last articles, we looked at the implementation of the passport-local authenticat ...

  3. firebase登录验证_如何使用Firebase通过三步向身份验证本机添加身份验证

    firebase登录验证 Authentication allows us to secure our apps, or limit access for non-user members. Auth ...

  4. uvm 形式验证_谈一谈IC flow中的形式验证

    By definition, formal verification is the use of tools that mathematically analyze the space of poss ...

  5. 前后端分离项目token怎么验证_微信端前后端分离开发中token验证和数据的获取...

    微信端前后分离开发中,授权认证,获取token和openid是必不可少的一步. 我们的思路是,每次调用接口前,判断cookie里面是否有token和openid,没有的话判断url参数中是否存在,没有 ...

  6. oauth身份验证方式_使用OAuth和Passport管理身份验证

    oauth身份验证方式 用户组列表和信息(UGLI)应用程序开始很好地成形. 现在,您可以通过在" 具有响应式Web设计的MEAN和UGLI CRUD "中设置的CRUD屏幕显示您 ...

  7. 网站如何经过身份验证_微服务架构如何保证安全性?

    网络安全已成为每个企业都面临的关键问题.几乎每天都有关于黑客如何窃取公司数据的头条新闻. 为了开发安全的软件并远离头条新闻,企业需要解决各种安全问题,包括硬件的物理安全性.传输和静态数据加密.身份验证 ...

  8. 网站如何经过身份验证_如何在微服务架构中实现安全性?

    首先为自己打个广告,我目前在某互联网公司做架构师,已经有5年经验,每天都会写架构师系列的文章,感兴趣的朋友可以关注我和我一起探讨,同时需要架构师资料的可以私信我免费送 作者 | Chris Richa ...

  9. laravel身份证验证_简单的Laravel登录身份验证

    laravel身份证验证 This article has been upgraded to work with Laravel 4.1.26 本文已升级为可与Laravel 4.1.26一起使用 T ...

最新文章

  1. c++ 继承访问控制初步
  2. “猜你喜欢” — 浅谈内容分发中的推荐系统
  3. 安卓Queue的使用
  4. android脚步---不同activity之间参数传递
  5. .net System.Web.Mail发送邮件
  6. 腾讯优图CVPR中标论文:不靠硬件靠算法,暗光拍照也清晰
  7. Java一套拳法刷掉n个遍历树的问题
  8. kettle软件的使用
  9. 物联卡中心:物联网卡代理商这么多,我怎么选?
  10. 支付宝提现至个人账户接口开发
  11. PS——使用 快速选择工具、魔法棒 抠图
  12. python把所有txt文件整合在一起(步道乐跑题库)
  13. python简易爬取喜马拉雅MP3
  14. EFR32BG22 的三种电源设计
  15. git clone速度太慢的解决办法
  16. pyflink执行任务问题总结
  17. Pygame实战:利用Python实现智能五子棋,实现之后发现我玩不赢它。
  18. 集成ci jenkins_使用jenkins fastlane第1 2部分将ci cd集成到多个环境中
  19. 大专生出身?mysql-uroot-p
  20. 手动彻底清除恶意网页病毒

热门文章

  1. 揭秘ARouter路由机制,源码+原理+手写框架
  2. expdp导出 schema_记录一则expdp任务异常处理案例
  3. leetcode 214 Shortest Palindrome
  4. 精确覆盖DLX算法模板
  5. CentOS7 linux下yum安装redis以及使用
  6. Linux环境下使用rpm包安装GitLab
  7. vue按照url地址访问出错404
  8. Java语言与sikuli配合
  9. Node.js学习之(第二章:exports和module.exports)
  10. 区分'方法'和'函数'