Nodejs express用户登录注册以及授权 bcrypt+JWT

16 篇文章 0 订阅
1 篇文章 0 订阅

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
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值