Nodejs expressユーザー登録及び授権bcrypt+JWT


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=754553913877770633