测试
@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)
})