1

我是护照 JWT 的新手,并且有此代码从客户端发送发布请求:

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

在服务器端,它通过护照正确路由并命中以下代码:

// 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 部分,而不是我需要检查数据库的子部分。我究竟做错了什么?

4

1 回答 1

1

好的,我想通了。我检查了我的令牌生成器功能是如何工作的。我正在使用猫鼬,它正在将用户模型的 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 的 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);
}
于 2016-08-27T19:26:20.327 回答