引入bcrypt和jwtSign函数
在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
}
在注册接口中使用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: '参数错误'
})
}
})
引入jwtCheck函数
在登录接口中使用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: '参数错误'
})
}
})
登录接口密码解密,并获取token
在需要用户登录验证的接口引入jwtCheck,在并接口中间件验证
引入bcrypt
在定义用户注册接口时使用bcrypt对密码进行加密.
安装所需依赖模块
注册接口密码加密
到此我们就实现了用户登录,注册,及token的生成和验证
登录时token的生成及其他接口调取时token的验证工具函数定义
在接口中间件使用验证函数,实例如下
router.get('/list', jwtCheck, (req, res) => {
res.send({
code: '000000',
msg: '验证成功'
})
})
文章为作者独立观点,不代表股票交易接口观点