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”的地方。 我們將使用JWT
和Crypto
從接收到的password
字符串生成hash
和salt
。 稍后將使用它來驗證用戶。
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令牌 ,該令牌將從客戶端的請求標頭中發送 。 我們還將創建一個具有optional
和required
屬性的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身份驗證