2016-12-24 77 views
-1

我創建了一個角度應用程序,我使用jwt來驗證每個api調用服務器。在客戶端,一旦用戶登錄,我在localStorage中將loggedIn設置爲true。然後在ui路由器上使用AuthService stateChangeStart事件,該事件檢查localStorage中的loggedIn是否爲true。使用localStorage的AngularJS身份驗證

我見過很多例子,他們在localStorage中保存用戶名,稍後檢查用戶名是否設置,或者不知道用戶是否被認證。但我的問題是,localStorage可以調節,任何人都可以將用戶名屬性設置爲某個值或將loggedIn設置爲true。

你對此的想法是什麼,有什麼我失蹤了。

+0

你能分享你的代碼 – Codesingh

回答

0

我做的是什麼,只要令牌存儲在localStorage的或更好的節省頭JSON如下

if (response.data.token) // response for successful login 
    { 
    let headers = { 
     ContentType : 'application/json', 
     access-token : response.data.token, 
     anyOtherHeader: 'xxx' 
    } 

    window.localStorage.setItem('headers',JSON.stringify(headers)); 
    } 

,只是檢查這個每當應用程序加載,如果它存在,如果它保持的方式它在$ rootScope

let headers = window.localStorage.getItem('headers'); 
if(headers){ 
    $rootScope.headers = JSON.parse(headers); 
    $timeout(function(){$scope.$apply()}) //to update your app about token 
} 

,每當您的令牌不被認證/未驗證/註銷從localStorage的刪除它和$ rootScope

window.localStorage.removeItem('headers') 
$rootScope.headers = undefined; 
$timeout(function(){$scope.$apply()}); //again to update your app about it 

通過適當的錯誤處理,它對我很好。雖然它可以鍛鍊,但不能被濫用。讓我知道如果這有助於:)

相關問題