JWT 未解码“JWT malformed";- 节点角度

2022-01-10 00:00:00 jwt node.js express angularjs javascript

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

Upon logging in I send a JSON web token to the client-side. I have a custom authInterceptor which sends the JSON web token back to the server side.

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

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.

当我关闭浏览器并返回站点时,JWT 无法解码.当 JWT 放在 encoding 函数下方时,它可以解码.我已经尝试了 jwt-simple 节点模块和 jsonwebtoken 节点模块,但我返回了同样的错误.

When I close the browser and return to the site, the JWT cannot decode. The JWT can decode when it is placed just under the encoding function. I have tried both the jwt-simple node module and the jsonwebtoken node modules, and I come back with the same error.

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

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 使用 jwt.encode()jwt.decode,jsonwebtoken 使用 jwt.sign()jwt.verify().这是我在控制台中得到的:

jwt-simple uses jwt.encode() and jwt.decode, and jsonwebtoken uses jwt.sign() and jwt.verify(). This is what I get in my console:

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

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

This is the authInterceptor on the client-side. 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);
    }
};
});

推荐答案

很高兴你明白了!对于后人来说,问题如下:JWT 由三个组件组成:标头、有效负载和签名(可以在这篇 toptal 帖子中找到一个很好、彻底的解释),所以当你拆分JWT 到带有 var token = req.headers.authorization.split('.') 的组件中,您分配给 token 的值仅指有效负载,而不是完整的智威汤逊.

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-simple 解码方法需要完整的令牌,而您只给它提供了要评估的有效负载,所以您的代码触发了jwt malformed"错误.在您的情况下,由于您在 Authorization 标头中使用 Bearer 在令牌之前,您可以使用 var token = req.headers.authorization.split(' ') 取而代之.

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. 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.

相关文章