简体   繁体   English

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

[英]JWT not decoding “JWT malformed” - Node Angular

Upon logging in I send a JSON web token to the client-side. 登录后,我将JSON Web令牌发送到客户端。 I have a custom authInterceptor which sends the JSON web token back to the server side. 我有一个自定义authInterceptor,它将JSON Web令牌发送回服务器端。

When I log in, everything works. 当我登录时,一切正常。 Go to different sub-pages, works great. 转到不同的子页面,效果很好。 This is because I have a function which either checks for Passport authentication or token authentication, and upon logging in the Passport authentication works. 这是因为我有一个函数可以检查Passport身份验证或令牌身份验证,并在登录Passport身份验证时工作。

When I close the browser and return to the site, the JWT cannot decode. 当我关闭浏览器并返回到站点时,JWT无法解码。 The JWT can decode when it is placed just under the encoding function. 当JWT放置在编码功能下时,它可以进行解码。 I have tried both the jwt-simple node module and the jsonwebtoken node modules, and I come back with the same error. 我已经尝试了jwt-simple节点模块和jsonwebtoken节点模块,我回来时遇到了同样的错误。

This is my custom function which checks for a valid token: 这是我的自定义函数,它检查有效的令牌:

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;
}

jwt-simple uses jwt.encode() and jwt.decode , and jsonwebtoken uses jwt.sign() and jwt.verify() . jwt-simple使用jwt.encode()jwt.decode ,jsonwebtoken使用jwt.sign()jwt.verify() This is what I get in my console: 这是我在我的控制台中得到的:

Here
eyJzdWIiOiI1NmEyZDk3MWQwZDg2OThhMTYwYTBkM2QiLCJleHAiOjE0NTYxOTEyNzQsImlhdCI6MTQ1NTMyNzI3NH0
VerySecretPhrase
And here....
{ [JsonWebTokenError: jwt malformed] name: 'JsonWebTokenError', message: 'jwt malformed' } 

This is the authInterceptor on the client-side. 这是客户端的authInterceptor。 I collect the token and set it in the request header: 我收集令牌并将其设置在请求标头中:

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);
    }
};
});

Glad you got it figured out! 很高兴你弄清楚了! The problem, for posterity, was the following: A JWT consists of three components, a header, the payload, and the signature ( a good, thorough explanation can be found in this toptal post ), so when you were splitting the JWT into components with var token = req.headers.authorization.split('.') , the value you were assigning to token referred to the payload only, rather than the full JWT. 对后人来说,问题如下:JWT由三个组成部分组成,一个标题,有效负载和签名( 在这个文章中可以找到一个好的,彻底的解释 ),所以当你将JWT分成组件时使用var token = req.headers.authorization.split('.') ,您分配给token的值仅指向有效负载,而不是完整的JWT。

Because the jwt-simple decode method expects the full token and you were only giving it the payload to assess, your code was triggering the 'jwt malformed' error. 因为jwt-simple解码方法需要完整的令牌而你只是给它评估的有效负载,所以你的代码触发了'jwt malformed'错误。 In your case, since you preceded the token with Bearer in your Authorization header, you could grab the full token with var token = req.headers.authorization.split(' ') instead. 在您的情况下,由于您在Authorization标头中的令牌前面有Bearer ,因此您可以使用var token = req.headers.authorization.split(' ')来获取完整令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM