完美通行证身份证号格式

    科技2023-11-26  85

    完美通行证身份证号格式

    In this article, I will share my knowledge of authenticating node.js server using passport.js and also a little stuff about protected routes and handle unauthorized requests.

    在本文中,我将分享我的知识,使用passport.js对node.js服务器进行身份验证,以及有关受保护路由和处理未授权请求的一些知识。

    I am using the following things.

    我正在使用以下内容。

    Node.js

    Node.js Express.js

    Express.js passport.js

    护照 JWT

    智威汤逊

    This article just gives you the basic understanding of authenticating users with passport.js and has nothing to relate with schema designing or other concepts using in node server.

    本文仅向您提供使用passport.js进行用户身份验证的基本知识,而与在节点服务器中使用架构设计或其他概念无关。

    The below paragraph is taken from the official website of passport.js

    以下段落摘自passport.js的官方网站

    Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

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

    I will try to explain the whole thing in steps so that you guys can easily understand

    我将尝试分步说明整个过程,以便大家轻松理解

    第1步 (Step # 1)

    Create an express application using express-generator to create a project by using the following command in command prompt.

    使用express-generator创建一个express应用程序,以通过在命令提示符下使用以下命令来创建一个项目。

    express [project-name]

    then cd into your project folder and open it in your favorite code editor mine is VS code Run the following command to install dependencies.

    然后cd到您的项目文件夹中,并在您最喜欢的代码编辑器中将其打开。我的代码是VS code。运行以下命令以安装依赖项。

    npm install

    第2步 (Step # 2)

    The project is set up and the next thing that we have to do is install passport.js

    该项目已设置,接下来我们要做的是安装passport.js

    We have to install a passport and passport-local using the following command at the root of the project directory

    我们必须使用以下命令在项目目录的根目录下安装通行证和本地通行证

    npm install passport passport-local --save

    passport-local is a passport strategy for authenticating with username and password.

    本地护照是用于使用用户名和密码进行身份验证的护照策略。

    By plugging into the passport this module allow us to authenticate the user with username and password.

    通过插入护照,该模块使我们可以使用用户名和密码对用户进行身份验证。

    步骤#3 (Step # 3)

    Once passport and passport-local was installed the next step is to require it into your project

    一旦安装了护照和本地护照,下一步就是要求将其纳入您的项目

    The project which we created previously has an app.js file and before using the routes that are using passport you have to require a passport and integrate it.

    我们之前创建的项目有一个app.js文件,在使用通行证的路线之前,您需要先获得通行证并将其集成。

    passport.use(new LocalStrategy({ usernameField: 'username', passwordField: 'password' }, User.authenticate())); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); app.use(passport.initialize());

    If you use mongoose then you also have to install passport-local-mongoose and add it in your user schema

    如果使用猫鼬,则还必须安装Passport-local-mongoose并将其添加到用户架构中

    const mongoose = require('mongoose'); const Schema = mongoose.Schema; const passportLocalMongoose = require('passport-local-mongoose'); const User = new Schema({ username: { type: String, required: true, }, email: { type: String, required: true } }); User.plugin(passportLocalMongoose); module.exports = mongoose.model('User', User);

    You are free to define your User schema in a way you like passport-local-mongoose add a username, hash, and salt field to store the username, hashed password, and salt values within your user schema.

    您可以自由地定义您的用户架构,就像护照本地猫鼬一样添加用户名,哈希和盐字段以在用户架构中存储用户名,哈希密码和盐值。

    Passport attaches the profile information to req.user and this occurs as a result of the serializeUser() and deserializeUser() functions. Passport.serialize and passport.deserialize are used to set id as a cookie in the user’s browser and to get the id from the cookie when it then used to get user info in a callback.

    Passport将配置文件信息附加到req.user,这是由serializeUser()和deserializeUser()函数导致的。 Passport.serialize和passport.deserialize用于在用户浏览器中将id设置为cookie,并在随后用于在回调中获取用户信息时从cookie获取id。

    After initializing the passport the next step is to make the APIs for registration of user or login user.

    初始化护照后,下一步是制作用于注册用户或登录用户的API。

    第4步 (Step # 4)

    I am making the separate file for the user route and import in app.js and pass it to app.use after initializing the passport.

    我正在为用户路由创建单独的文件,并在初始化护照后将其导入app.js并将其传递给app.use。

    let usersRouter = require('./routes/users'); passport.use(new LocalStrategy({ usernameField: 'username', passwordField: 'password' }, User.authenticate())); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); app.use(passport.initialize()); app.use('/users', usersRouter);

    The user routes file is looking like this

    用户路由文件看起来像这样

    const express = require('express'); const router = express.Router(); const userHandler = require('../handlers/users'); router.route('/register') .post(userHandler.register); router.route('/login') .post(userHandler.login); module.exports = router;

    These two routes ‘/register’ and ‘/login’ are the basic that we discuss in this article. I have made the separate file for callback functions and require them as userHandler and pass it to routes.

    这两个路由“ / register”和“ / login”是我们在本文中讨论的基础。 我为回调函数制作了单独的文件,并要求它们作为userHandler并将其传递给路由。

    First, we discuss the Registration API

    首先,我们讨论注册API

    The register function in the handler file that is required in user routes and pass to ‘/register’ endpoint looks like this.

    用户路由中需要的处理程序文件中的register函数,并传递给'/ register'端点,如下所示。

    const auth = require('../common/auth'); exports.register = (req, res, next) => { User.register(new User({ username: req.body.username, email: req.body.email }), req.body.password, (err, user) => { if (err) { return next(err); } auth.getData(user) .then(data => { return res.json({ success: 'success', data }); }) .catch(err => { return next({ message: 'database error'}); }); }); };

    User.register function is only available if you add passport-local-mongoose in the user schema and it will simply create a new user in the database or returns an error if the user with a given username already exists.

    仅当在用户模式中添加Passport-local-mongoose时,User.register函数才可用,并且它将仅在数据库中创建一个新用户,或者如果已经存在具有给定用户名的用户,则返回错误。

    auth.getData is a function that takes the user data sealed it using Iron generate the JWT token and return the user data

    auth.getData是一个函数,使用Iron将用户数据密封起来,生成JWT令牌并返回用户数据

    const verify = require('../common/verify'); exports.getData = user => new Promise(async (resolve, reject)=>{ try { const userData = { _id: user._id, username: user.username, email: user.email }; const seal = await Iron.seal(userData, process.env.sealPassword, Iron.defaults); const token = verify.getToken({ data: seal }); return resolve({ token, user: userData }); } catch (error) { return reject(error); } });

    The seal password must be saved somewhere locally usually we keep it in the .env file and not share with anyone ( must add .env file in .gitignore file )

    印章密码必须保存在本地,通常我们将其保存在.env文件中,而不与任何人共享(必须在.gitignore文件中添加.env文件)

    verify.getToken function takes the sealed user and returns the JWT token which we send in the response of API call to be stored in Front end application and use further for accessing other private APIs.

    verify.getToken函数接受密封的用户,并返回JWT令牌,该令牌在API调用响应中发送并存储在前端应用程序中,并进一步用于访问其他私有API。

    const jwt = require('jsonwebtoken'); exports.getToken = function (user, expiresIn) { return jwt.sign(user, process.env.secretKey, { expiresIn: expiresIn || 3600 }); };

    jsonwebtoken is also using a secret key to generate a token this secret key must be stored somewhere locally usually in the .env file.

    jsonwebtoken还使用秘密密钥生成令牌,该秘密密钥通常必须存储在本地的.env文件中。

    This is all for user registration API. Run the server using

    这全部用于用户注册API。 使用以下命令运行服务器

    npm start

    Make sure you have connected the database ( local or deployed somewhere ) Hit the following endpoint using postman or CURL

    确保已连接数据库(本地或部署在某个地方),使用邮递员或CURL命中以下端点

    POST http://localhost:3000/users/register

    also include username and password as a JSON object in a body and you will get the user data along with the JWT token.

    还将用户名和密码作为JSON对象包含在正文中,您将获得用户数据以及JWT令牌。

    For Login

    登录

    The login call back in userHandler is written as

    userHandler中的登录回叫写为

    const auth = require('../common/auth'); const passport = require('passport'); exports.login = (req, res, next) => { passport.authenticate(`local`, (err, user, info) => { if (err) { return next({ message: 'database error}); } if (info) { return next({ message: info.message }); } if (!user) { return next({ message: 'No user found'}); } req.logIn(user, err => { if (err) { return next({ message: 'databse error'}); } auth.getData(user) .then(data => { return res.json({ success: 'success', data }); }) .catch(err => { return next({ message: 'database error', data: err }); }); }); })(req, res, next); };

    Passport. authenticate first param is a strategy that we use, in this case, it is local’

    护照。 验证第一个参数是我们使用的策略,在这种情况下,它是本地的”

    and it returns the user in a callback which is used by our auth.getData function to generate a token and return as a response to Front end application.

    并在回调中返回用户,我们的auth.getData函数使用该回调生成令牌并作为对前端应用程序的响应返回。

    I have tried to keep the article as simple as I can but if you guys still have some confusion or questions please refer to the following git repository

    我试图使本文尽可能简单,但是如果你们仍然有一些困惑或疑问,请参阅以下git信息库

    Github链接 (Github Link)

    If you find any error please report.

    如果发现任何错误,请报告。

    Thanks!

    谢谢!

    翻译自: https://medium.com/@talhanousher/node-js-authentication-using-passport-js-226839952a46

    完美通行证身份证号格式

    Processed: 0.014, SQL: 8