完美通行证身份证号格式

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.jsNode.js
  • Express.jsExpress.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

完美通行证身份证号格式


http://www.taodudu.cc/news/show-3462577.html

相关文章:

  • 完美通行证身份证号格式_如何渲染3D足球通行证网络
  • 坎公骑冠剑普系角色德魯伊坎納属性、专武曝光
  • java康纳塔评测_CANNONATA康纳塔 JAVA发布2016款终极赛车
  • java康纳塔22s评测_Pico G2 4K和奇遇2s的测评对比 上
  • 从学习如何学习开始
  • 《Option Volatility Pricing》阅读笔记之 Theoretical Pricing Model(理论定价模型)
  • (gcd,lcm,互质) 康纳的表情包--SDUT,Wolf and Rabbit--HDOJ
  • 【历史上的今天】2 月 5 日:雅达利创始人出生;改变战争命运的 Colossus 计算机问世;希捷收购康纳外设
  • 2017 山东理工第九届校赛 C 康纳的表情包
  • Java使用mysql_connector驱动包连接数据库
  • java康纳塔碳纤维硬吗,碳纤维车身是最硬的吗 最奢侈的汽车材料就是它
  • java终结者怎么样_终结者6:丹妮与约翰康纳相比怎么样?她绝对也是个好领袖!...
  • java康纳塔和费罗切_这里是广告:这种配置不要六千?你敢信?
  • SDUT 3917 康纳的表情包
  • java康纳塔评测_Java地位无可动摇的12个原因C_服务器评测与技术-中关村在线
  • FullCodePress采访:蒂姆·康纳(Tim Connor),新西兰队
  • 1130 mysql 服务器_mysql 连接远程连接服务器 1130错误
  • 康纳的表情包
  • mysql 远程登陆设置_mysql远程登陆设置
  • 原Borland Delphi研发部程序员Joe C. Hecht讲述自己离开Borland公司作为个体户程序员独立单干接活谋生的故事
  • cct一级计算机考试试题,cct一级计算机考试单选题.doc
  • 面试常问经典Java算法题(附带参考代码)
  • 计算机基础知识 上机 xp 试题,计算机应用基础上机指导及试题汇编
  • 计算机网络 复习题(带答案)
  • 数据结构与算法习题库
  • Java基础50题
  • 全国计算机等级考试试题研究组,全国计算机等级考试题研究中心
  • python企业面试题250道
  • c语言编程带铰钢架问题,C语言编程练习题绝对经典
  • PTA 数据结构部分选择题

完美通行证身份证号格式_使用通行证js进行节点js身份验证相关推荐

  1. 完美通行证身份证号格式_如何渲染3D足球通行证网络

    完美通行证身份证号格式 Pass network analysis has long been a popular visualization method amongst football anal ...

  2. SpringBoot自定义注解实现身份证号格式校验

    背景 ​ 身份证的组成部分较为复杂, 如果仅使用正则表达式的话, 有些情况也无法校验出来, 例如正确的证件号为513334200310119074, 如果把最后一位变成9, 则是一个错误的证件号, 但 ...

  3. 验证身份证号 格式问题

    导入的时候 验证身份证号的格式问题 if(!sfzh.equals("")&&isIDNumber(sfzh) == false){returnMap.put(&q ...

  4. 使用js验证身份证号格式以及身份证号中的生日验证

    由于不管是测试项目练手还是实际项目开发,都应该考虑数据的严密性和软件的通俗易懂的实用性,下面是我用js实现的验证身份证号格式以及身份证号中的生日验证代码 //生日移出点击事件验证身份证号中的生日验证 ...

  5. SQL 校验身份证号格式

    调用示例: SELECT  dbo.[fn_IDCardChk]('123')  /* --------------------------- 校验身份证号是否有效 成功返回1 失败返回0Jacker ...

  6. JS 身份证号格式验证

    var idcard = data.field.idcard; if(!/(^\d{15}$)|(^\d{17}(x|X|\d)$)/.test(idcard)){ //验证身份证号15位或18位la ...

  7. 用python判断身份证号性别_验证身份证号的Python脚本

    引用 a[0], a[1], a[2], a[3], ..., a[16], a[17] 其中a[i]表示第i位数字,i=0,1,2,...,17,如果最后一位(校验位)是X,则a[17]=10 每一 ...

  8. JS校验手机号和身份证号格式

    1:校验手机号 //JS正则表达式校验手机号function isPoneAvailable(poneInput) {var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;if ( ...

  9. java验证身份证号格式

    //15位到18位的身份证号 public static boolean checkIdCard(String idCard) { String regex = "^[1-9]\\d{7}( ...

最新文章

  1. linux 内核 初始化失败,300分求内核初始化及启动中出现的问题,
  2. 一些随笔,我有故事,你有酒吗
  3. UTF-8文本文件头部出现乱码“锘*”的问题及解决方法
  4. 代码生成器的存在价值 选择自 mechiland 的 Blog
  5. 线程的run()方法带参情况
  6. 关于将表单上传到服务器
  7. 【PostgreSQL-9.6.3】表继承
  8. OFFICE技术讲座:设置调整字间距(kern)后,标点就不压缩
  9. win10鼎信诺为什么安装不了_win10安装软件没反应怎么办
  10. 数据结构1800题-错题集-第二章
  11. Windows下安装Nutch
  12. 计算机公式里qf是什么,计算公式
  13. android壁纸设置,android设置壁纸 的方法
  14. 2018年苹果年费支付失败真正的原因
  15. 送你一个励志故事—掌握这些你也可能拿到腾讯offer
  16. MyEclipse小结
  17. (PTA)6-9 字符串压缩
  18. 基于LSTM-CNN的地铁短时客流量预测
  19. 全文翻译【Scaled-YOLOv4: Scaling Cross Stage Partial Netw】
  20. 【Linux】第二篇:Linux环境及开发工具

热门文章

  1. 国企招聘:中央广播电视总台2023年公开招聘110名工作人员公告!
  2. PyTorch 手把手教你实现 MNIST 数据集
  3. 国内优秀的java开源saas项目分享
  4. 造个计算机--1、设计运算器
  5. 申请@msn.com的邮箱最新网址
  6. window操作系统搭建Spark开发调试环境
  7. 典型计算机控制系统的基本框图6,计算机控制系统试题
  8. Java中SQL动态封装工具类--Java自学网
  9. 装完系统后,蓝屏/黑屏/开不了机
  10. 手把手教你使用 Python 制作贪吃蛇游戏,才发现原来制作起来很简单ǃ