【express学习笔记】使用jwt完成简单的登录注册授权操作

测试

@url=http://localhost:3001/api
@json=Content-Type: application/json
###所有用户
get {{url}}/users

###注册
post {{url}}/register
{{json}}

{
    "username": "user4",
    "password": "123456"
}
###登录
post {{url}}/login
{{json}}

{
    "username": "user3",
    "password": "123456"
}
###个人信息
get {{url}}/profile
Authorization: Bearer token

安装REST client

model.js

const { Schema } = require('mongoose')
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/express-auth', {
    useCreateIndex: true,
    useNewUrlParser: true
})
.then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));

const UserSchema = new mongoose.Schema({
    username: { type: String, unique: true},
    password: { 
        type: String, 
        set(val) {
            return require('bcrypt').hashSync(val, 4)
        }
    },
})

const User = mongoose.model('User', UserSchema)

// User.db.dropCollection('users')

module.exports = { User }

连接mongodb

mongoose.connect('mongodb://localhost:27017/express-auth', {
useNewUrlParser: true})

mongoDB 模型

const User = mongoose.model('User', UserSchema)

导出,在其他文件使用

module.exports = { User }

server.js

const { User } = require('./models')

const express = require('express')

const app = express()
const SECRET = 'fakeSecret'
app.use(express.json())
const jwt = require('jsonwebtoken')

app.get('/api/users', async(req, res) => {
    const users = await User.find()
    res.send(users)
})

app.post('/api/register', async(req, res) => {
    const user = await User.create({
        username: req.body.username,
        password: req.body.password,
    })
    res.send(user)
})

app.post('/api/login', async(req, res) => {
    const user = await User.findOne({
        username: req.body.username
    })
    if(!user) {
        return res.status(422).send({
            message: '用户名不存在'
        })
    }
    const isPasswordValid = require('bcrypt').compareSync(
        req.body.password,
        user.password
    )
    if(!isPasswordValid) {
        return res.status(422).send({
            message: '密码错误'
        })
    }
    //生产token
    const jwt = require('jsonwebtoken')
    const token = jwt.sign({
        _id: String(user._id)
    },SECRET)
    res.send({
        user,
        token
    })
})

const auth = async(req, res, next) => {
    const raw = String(req.headers.authorization).split(' ').pop()
    const { id } = jwt.verify(raw, SECRET)
    req.user = await User.findById(id)
    next()
}

app.get('/api/profile', auth, async(req, res) => {
    res.send(req.user)
})

app.listen(3001, () => {
    console.log('http://localhost:3001')
})

使用jwt 以id作为playload,secret一般放在env中

    const jwt = require('jsonwebtoken')
    const token = jwt.sign({
        _id: String(user._id)
    },SECRET)

shiyongsuth中间件验证

const auth = async(req, res, next) => {
    const raw = String(req.headers.authorization).split(' ').pop()
    const { id } = jwt.verify(raw, SECRET)
    req.user = await User.findById(id)
    next()
}

app.get('/api/profile', auth, async(req, res) => {
    res.send(req.user)
})

gitee代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值