npm i bcrypt
密码加密
set(val) {
return require('bcrypt').hashSync(val, 10) // 散列强度/指数
}
密码解密比对
const isPasswordValid = require('bcrypt').compareSync(
req.body.password,
user.password
)
生成token
npm i jsonwebtoken
const SECRET = 'secretmiyao'
const jwt = require('jsonwebtoken')
const token = jwt.sign({
id: String(user._id),
},SECRET) // 第二个参数为密钥,全局表示唯一,不应该存在git里,应该是本地的东西
token 使用
//前端应该把token发送在header里
Authorization: Bearer imatokenimatokenimatokenimatokenimatoken;
token 解析
//解析 token
const jwt = require('jsonwebtoken')
app.get('/api/profile', async (req, res) => {
const raw= String(req.String(req.headers.authorization).split(' ').pop())
const tokenData = jwt.verify(raw, SECRET)
// 可以直接 { id } = jwt.verify(raw, SECRET)
})
中间件
//中间件
const auth = async (req, res, next) => {
const raw= String(req.String(req.headers.authorization).split(' ').pop())
const { id } = jwt.verify(raw, SECRET)
req.user = awai User.findById(id) // 写到 req里这样,下一个中间件也可以用了
next()
}
app.get('/api/profile', auth(), async (req, res) => {
res.send(req.user)
})
参考:
- https://juejin.im/post/5cd277285188253f690459ed
- https://www.bilibili.com/video/av49391383?from=search&seid=7545539138774107633