JWT没有解码"JWT格式错误" - Node Angular

Les*_*aul 3 javascript node.js express jwt angularjs

登录后,我将JSON Web令牌发送到客户端.我有一个自定义authInterceptor,它将JSON Web令牌发送回服务器端.

当我登录时,一切正常.转到不同的子页面,效果很好.这是因为我有一个函数可以检查Passport身份验证或令牌身份验证,并在登录Passport身份验证时工作.

当我关闭浏览器并返回到站点时,JWT无法解码.当JWT放置在编码功能下时,它可以进行解码.我已经尝试了jwt-simple节点模块和jsonwebtoken节点模块,我回来时遇到了同样的错误.

这是我的自定义函数,它检查有效的令牌:

function checkAuthentication(req, res, next){
  if (!req.headers.authorization) {
     return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
  }
  console.log("Here");
  var token = req.headers.authorization.split('.')[1];
  console.log(token);
  console.log(config.secret);
  var payload = null;
  try {
    console.log("And here....");
    payload = jwt.decode(token, config.secret);
    console.log(payload);
  }
  catch (err) {
    console.log(err);
    return false;
  }

  if (payload.exp <= moment().unix()) {
    return false;
  }
  req.user = payload.sub;
  return true;
}
Run Code Online (Sandbox Code Playgroud)

jwt-simple使用jwt.encode()jwt.decode,以及jsonwebtoken使用jwt.sign()jwt.verify().这是我在我的控制台中得到的:

Here
eyJzdWIiOiI1NmEyZDk3MWQwZDg2OThhMTYwYTBkM2QiLCJleHAiOjE0NTYxOTEyNzQsImlhdCI6MTQ1NTMyNzI3NH0
VerySecretPhrase
And here....
{ [JsonWebTokenError: jwt malformed] name: 'JsonWebTokenError', message: 'jwt malformed' } 
Run Code Online (Sandbox Code Playgroud)

这是客户端的authInterceptor.我收集令牌并将其设置在请求标头中:

app.factory('httpInterceptor', function($q, $store, $window) {
return {
    request: function (config){
        config.headers = config.headers || {};
        if($store.get('token')){
            var token = config.headers.Authorization = 'Bearer ' + $store.get('token');
        }
        return config;
    },
    responseError: function(response){
        if(response.status === 401 || response.status === 403) {
            $window.location.href = "http://localhost:3000/login";
        }
        return $q.reject(response);
    }
};
});
Run Code Online (Sandbox Code Playgroud)

Ben*_*ams 9

很高兴你弄清楚了!对后人来说,问题如下:JWT由三个组成部分组成,一个标题,有效负载和签名(在这个文章中可以找到一个好的,彻底的解释),所以当你将JWT拆分成组件时with var token = req.headers.authorization.split('.'),您指定的值token仅指向有效负载,而不是完整的JWT.

因为jwt-simple解码方法需要完整的令牌而你只是给它评估的有效负载,所以你的代码触发了'jwt malformed'错误.在您的情况下,由于您在BearerAuthorization标头中使用了令牌,因此您可以获取完整令牌var token = req.headers.authorization.split(' ').