后端开发中,用户登录,注册,及其他接口的token验证是必需的,以前开发时会在用户登录时存一个session,但是现在token验证的方式更多也更好。这篇文章教大家实现密码加密保存及解密验证,还有token生成及验证。
安装所需依赖模块
npm i bcrypt jsonwebtoken
1. 登录时token的生成及其他接口调取时token的验证工具函数定义
在util文件创建个jwt.js文件
const jwt = require('jsonwebtoken')
const jwtKey = 'junkaicool' // token生成的密匙,根据自己需求定义
const jwtSign = (data) => { // token生成函数,有效时间为一个小时
const token = jwt.sign(data, jwtKey, {expiresIn: 60 * 60})
return token
}
const jwtCheck = (req, res, next) => { // token验证函数
const token = req.headers.token
jwt.verify(token, jwtKey, (err, data) => {
if (err) {
res.send({
code: '999999',
msg: 'token无效'
})
} else {
req.jwtInfo = data
next()
}
})
}
module.exports = {
jwtSign,
jwtCheck
}
2.注册接口密码加密
在定义用户注册接口时使用bcrypt对密码进行加密.
- 引入bcrypt
const bcrypt = require('bcrypt')
- 在注册接口中使用bcrypt加密
router.post('/reg', (req, res) => {
const {username, password} = req.body
if (username && password) {
const hashPwd = bcrypt.hashSync(password, 10) // 使用bcrypt.hashSync方法生成密文密码
userModel.create({
username, password: hashPwd
}, (err, data) => {
if (err) {
res.send({
code: '111112',
msg: '注册失败'
})
} else {
res.send({
code: '000000',
msg: '注册成功'
})
}
})
} else {
res.send({
code: '111111',
msg: '参数错误'
})
}
})
3.登录接口密码解密,并获取token
- 引入bcrypt和jwtSign函数
const bcrypt = require('bcrypt')
const {jwtSign} = require('../util/jwt')
- 在登录接口中使用bcrypt解密
router.post('/login', (req, res) => {
const {username, password} = req.body
if (username && password) {
userModel.find({username}, (err, data) => {
if (err || !data.length) {
res.send({
code: '111112',
msg: '登录失败'
})
} else {
const isPwdValid = bcrypt.compareSync(password, data[0].password) // 使用bcrypt.compareSync方法验证密码
if (isPwdValid) {
const token = jwtSign({_id: data[0]._id}) // 用引入的jwtSign方法生成token并返回
res.send({
code: '000000',
msg: '登录成功',
data: {
token
}
})
} else {
res.send({
code: '111113',
msg: '密码错误'
})
}
}
})
} else {
res.send({
code: '111111',
msg: '参数错误'
})
}
})
4.在需要用户登录验证的接口引入jwtCheck ,在并接口中间件验证
- 引入jwtCheck函数
const {jwtCheck} = require('../util/jwt')
在接口中间件使用验证函数,实例如下
router.get('/list', jwtCheck, (req, res) => {
res.send({
code: '000000',
msg: '验证成功'
})
})
到此我们就实现了用户登录,注册,及token的生成和验证