Express 为什么我的Jwt令牌没有被提取?
我是passport JWT的新成员,有以下代码从客户发送post请求:Express 为什么我的Jwt令牌没有被提取?,express,mongoose,jwt,passport.js,express-jwt,Express,Mongoose,Jwt,Passport.js,Express Jwt,我是passport JWT的新成员,有以下代码从客户发送post请求: export function checkLogin() { return function( dispatch ) { //check if user has token let token = localStorage.getItem('token'); if (token != undefined) { //fetch user deets var config = {
export function checkLogin() {
return function( dispatch ) {
//check if user has token
let token = localStorage.getItem('token');
if (token != undefined) {
//fetch user deets
var config = {
headers: {'authorization': token, 'content-type': 'application/json'}
};
axios.post(`${API_URL}/login`, null, config)
.then(response => {
console.log('response is:', response);
})
.catch((error)=> {
console.log(error);
});
}
//user is anonymous
}
此请求在发送时,在头文件中包含令牌,如下所示:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
authorization:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NzIzMTg2MDE5NTd9.SsCYqK09xokzGHEVFiHtHmq5_HvtWkb8EjQJzwR937M
Connection:keep-alive
Content-Length:0
Content-Type:application/json
DNT:1
Host:localhost:3090
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36
在服务器端,它通过passport正确路由并点击以下代码:
// setup options for JWT strategy
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: config.secret,
ignoreExpiration: true
};
//create JWT strategy
const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done ) {
console.log('payload:',payload); // --> payload: { iat: 1472318601957 }
// see if the user ID in the payload exists in our database
User.findById(payload.sub, function(err, user) {
if (err) {
console.log('auth error');
return done( err, false );
}
//if it does, call 'done' function with that user
if (user) {
console.log('user authd:', user);
done( null, user);
//otherwise, call 'done' function without a user object
} else {
console.log('unauthd user'); //--> gets here only
done( null, false);
}
});
});
问题是extractJwt函数只返回iat部分,而不是我需要检查db的子部分。我做错了什么?好吧,我知道了。我检查了我的令牌生成器函数是如何工作的。我使用的是mongoose,它将用户模型的id传递给令牌,如下所示:
function tokenForUser(user) {
const timestamp = new Date().getTime();
//subject and issued at time
return jwt.encode({ sub: user.id, iat: timestamp }, config.secret);
}
我查看了发送到这个函数中的实际模型,结果发现mongoose添加了一个带有密钥的id,而不是id。一旦我将其更改为此,一切正常
function tokenForUser(user) {
const timestamp = new Date().getTime();
//subject and issued at time
const userid = user['_id'];
return jwt.encode({ sub: userid, iat: timestamp }, config.secret);
}
iat 1472318601957是什么意思?函数tokenForUser(user){const timestamp=new Date().getTime();//主题并在返回jwt.encode时发出({sub:user.id,iat:timestamp},config.secret);}