passport身份验证
by Antonio Erdeljac
通过安东尼奥·埃尔德雅克
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存储库 。
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的更多信息。
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
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');
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');
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'));
I will be using Postman to send requests to our server.
我将使用邮递员 发送请求到我们的服务器。
Our server accepts the following body:
我们的服务器接受以下主体:
{
"user": {
"email": String,
"password": String
}
}
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.
现在,让我们测试仅验证身份的路由。
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:
响应:
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:
您可以通过以下方式与我联系:
Check out my app SwipeFeed.
查看我的应用程序SwipeFeed 。
passport身份验证