我试图在后端进行身份验证,以便只有正确的用户才能获得正确的数据。
App.js
const express = require('express');
const app = express();
const {mongoose} = require('./db/mongoose');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken')
//load Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//CORS Middleware
app.use(function(req, res, next) {
req.header("Content-Type: application/x-www-form-urlencoded");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", " GET, POST, OPTIONS, PUT, PATCH, DELETE")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-access-token, x-refresh-token");
res.header(
'Access-Control-Expose-Headers',
'x-access-token, x-refresh-token'
);
next();
})
为了实现我的目标,我创建了身份验证方法。
//aunthenticate middleware
let authenticate = (res, req, next) => {
let token = res.header('x-access-token');
jwt.verify(token, User.getJWTSecret(), (err, decoded) => {
if (err) {
res.status(401).send(err);
console.log(err)
} else {
req.user_id = decoded._id;
next();
}
})
}
我必须进入用户模型
const { User } = require('./db/models/users.model');
关键是每个用户都应该有自己的调度记录。因此
app.get('/dispatch', authenticate, (req, res) => {
Dispatch.find({
_userId: req.user_id
}).then((dispatch) => {
res.send(dispatch);
}).catch((e) => {
res.send(e);
})
})
我们得到的所有提示都在
Users.model.js
const mongoose = require("mongoose");
const _ = require("lodash");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const crypto = require("crypto")
const jwtSecret = "XXXXXXXXXXX";
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 1,
trim: true,
unique: true
},
password: {
type: String,
required: true,
minlength: 8
},
sessions: [{
token: {
type: String,
required: true
},
expiresAt: {
type: Number,
required: true
}
}]
});
//Model Methods
UserSchema.statics.getJWTSecret = () => {
return jwtSecret;
}
const User = mongoose.model('User', UserSchema);
module.exports = { User };
当我运行get分派方法是postman时,我的终端上的错误是jsonwebtokenError: jwt必须是字符串
发布于 2021-05-06 10:35:55
正如错误提示的那样,您的问题在于如何设置令牌,因为您所提供的值似乎不属于字符串类型。
现在,我看不到您用共享的代码设置令牌的位置,但是要解决这个问题,只需确保传递一个字符串化的值即可。
我建议你用toString
来强迫它
jwt.sign(jwtValue.toString(), jwtSecret, { expiresIn: '1800s' });
如果要存储对象,也可以使用字符串:
jwt.sign(JSON.stringify(jwtValue), jwtSecret, { expiresIn: '1800s' });
发布于 2022-05-19 12:53:45
当您从完整对象提供的cookie中取出令牌时,您需要从cookie中提取令牌。这个错误也出现在我这里,如果您想要使用这个方法,因为您的代码和我的代码有点不同,您只需要从标头中获取令牌,而不需要从整个对象中获取标记,而且您的jwt_secret也是字符串。
https://stackoverflow.com/questions/67415891
复制相似问题