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)
token使用
Authorization: Bearer imatokenimatokenimatokenimatokenimatoken;
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)
})
中間部品
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)
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=754553913877770633