2016-02-12 47 views
1

這個問題很明顯:我的瀏覽器上存儲了令牌。當我登錄時,服務器端認證中間件使用Passport來認證我。但是,當我關閉並重新打開瀏覽器窗口時,令牌仍然存在,但護照不知道我是誰。角度節點 - 在打開新的瀏覽器窗口時向服務器發送令牌

如何從客戶端獲取令牌到服務器端?

以下是我的代碼。

app.get('/main', ensureAuthenticated, function(req, res, next) { 
    // thingToSend gets sent the first time, I will modify it 
    // later so it doesn't resend token if token exists 
    var thingToSend = { 
     token: createSendToken(req.user, config.secret), 
     id: req.user._id, 
     username: req.user.username, 
     authorization: req.user.authorization 
    };  
    res.render('main.ejs', thingToSend); 
}); 

function ensureAuthenticated(req, res, next) { 
    if (req.isAuthenticated()) { 
     return next(); 
    } else { 
     res.redirect('/login_page'); 
    } 
} 

回答

0

所以回答我的問題是讓我在app.config中注入的請求攔截。請求攔截收集令牌,並且我的初始會話後,可隨時請求攔截器附着的令牌請求報頭:

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

然後使用函數ensureAuthentication()在初始登錄到檢查或者a)Passport.authentication,或b)的檢查隨後在自定義函數checkAuthentication()之後的令牌認證。

function ensureAuthenticated(req, res, next) { 
    if (req.isAuthenticated()) { 
     return next(); 
    } else { 
     var x = checkAuthentication(req, res, next); 
     if (x === true) { 
      return next(); 
     } else { 
      res.redirect('/login_Page'); 
     } 
    } 
} 

任何人都希望看到checkAuthentication()或我的故障診斷關於JSON網絡令牌的相關問題上取得進展:JWT not decoding "JWT malformed" - Node Angular

1

您應該向角度應用程序添加請求攔截器,並將您的身份驗證令牌與發送到服務器的每個請求一起附加。

瞭解更多關於此請求攔截器:https://docs.angularjs.org/api/ng/service/$http

+0

想通了幾個小時回來,我工作的一個功能。如果您有興趣查看它,我會在找出修復程序時發佈該功能。 –

相關問題