2016-02-13 79 views
2

登錄後,我向客戶端發送JSON Web令牌。我有一個自定義authInterceptor,它將JSON Web令牌發送回服務器端。JWT未解碼「JWT格式錯誤」 - 節點角度

當我登錄時,一切正常。轉到不同的子頁面,效果很好。這是因爲我有一個函數可以檢查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; 
} 

智威湯遜,簡單使用jwt.encode()jwt.decode和jsonwebtoken使用jwt.sign()jwt.verify()。這是我在控制檯中得到的結果:

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

這是客戶端的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); 
    } 
}; 
}); 
+1

你有沒有console.logged你的catch塊中的錯誤? –

+0

Noob錯誤,我應該這樣做。這是我得到: {[JsonWebTokenError:jwt malformed]名稱:'JsonWebTokenError',消息:'jwt malformed'} –

+1

我不確定這是否是您的問題,但json Web令牌應該是'req.headers.Authorization'的全部內容,所以當你分割('。')'並且抓取索引1的元素時,這實際上是有效載荷,所以你有變量'token'指向負載而不是完整的智威湯遜。如果你之前還沒有和JWT合作過,[這篇文章](http://www.toptal.com/web/cookie-free-authentication-with-json-web-tokens-an-example-in-laravel- and-angularjs)對他們有很好的解釋。 –

回答

5

很高興你明白了!後代的問題如下:JWT包含三個組件,一個標題,有效負載和簽名(a good, thorough explanation can be found in this toptal post),所以當您將JWT拆分爲具有var token = req.headers.authorization.split('.')的組件時,將分配給token的值只有有效載荷,而不是完整的JWT。

由於jwt-simple解碼方法需要完整的令牌,並且您只給它有效負載進行評估,所以您的代碼正在觸發'jwt malformed'錯誤。在你的情況下,因爲你在授權標題前加上了Bearer,你可以用var token = req.headers.authorization.split(' ')代替完整的標記。

+1

有幫助。謝謝 – grant