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.pswp.cn/news/394125.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394125.shtml
英文地址,請注明出處:http://en.pswp.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…