2

大家好,我創建一個RESTful API與身份驗證令牌(Rails的4 +設計),而且我管理的CORS實現與寶石(機架CORS),但現在我想通過API使用angular.js如何使用angular.js中的令牌管理身份驗證?

爲此,我這樣做:

var app = angular.module('models'); 

app.factory('Session',['$resource',function($resource){ 
    var Session = $resource(
     'http://api.creositios.dev/sessions/:id', 
     {}, 
     { 
      create: { method: 'POST'}, 
      delete: { method: 'DELETE', params: { id: '@id'} } 
     } 
    ); 
    return Session; 
}]); 

這是我的控制器

app = angular.module('controllers'); 

app.controller('SessionCtrl',['$scope','Session',function($scope,Session){ 

    $scope.new_session = function(){ 
    $scope.session = Session.create({email: '[email protected]', password: '12345678'}); 
    }; 

}]); 

到目前爲止,我還沒有與執行問題。我的問題是不知道如何管理返回我工廠的令牌。

什麼是用angular.js管理用戶的token的良好實踐,並在angular.js中的differents控制器中驗證用戶?

這是我第一個使用令牌進行身份驗證的應用程序。建議非常感謝!

回答

5

通常的做法是將安全邏輯放入服務中,並使用httpInterceptor在請求中設置令牌。

安全服務。

angular.module('security') 
    .factory('Security', ['$http', function ($http) { 

     var token; 

     function login(email, password) { 
      return $http.post('/auth/login', {email: email, password: password}) 
       .then(function (response) { 

        if (response.data.token) { 
         token=response.data.token; 
        } 
       }); 
     } 

     function getToken(){ 
      return token; 
     } 

     return { 
      login:login, 
      token:getToken 
     };  
}]); 

這個特定的登錄方法可以被登錄控制器使用,例如:當用戶登錄時返回的令牌被存儲。

現在可以將令牌的攔截器添加到您的所有HTTP請求

.factory('authorizationInterceptor', ['Security', function (Security) { 
     return { 
      request: function (config) { 
       var token=Security.getToken(); 
       config.headers = config.headers || {}; 
       if (token) { 
        config.headers.Authorization = 'Bearer ' + token; 
       } 
       return config; 
      } 
     }; 
    }]); 

當的Bootstrap的應用,不要忘記添加攔截

 .config(['$httpProvider',function ($httpProvider) { 
      $httpProvider.interceptors.push('authorizationInterceptor'); 
     }]); 

現在令牌會在每個http請求上設置,如果出現故障,您將如何處理,然後由您決定。

例如,您可以添加另一個響應攔截器,如果獲得401或403響應重定向到登錄頁面等等