为什么我的Jwt令牌没有被提取?

时间:2016-08-27 18:20:38

标签: express mongoose jwt passport.js express-jwt

我是护照JWT的新手,并让此代码从客户发送邮件请求:

private async void web_LoadCompleted(object sender, NavigationEventArgs e)
{
  Object[] parameters = new Object[1]; 
  await yourBrowser.Document.InvokeScript("scriptName", parameters);
}

并且此请求在标题中发送罚款,如下所示:

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

问题是extractJwt函数只返回iat部分,而不是我需要检查db的子部分。我做错了什么?

1 个答案:

答案 0 :(得分:1)

好的,我明白了。我检查了我的令牌生成器功能是如何工作的。我正在使用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为key _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);
}