簡體   English   中英

如何在angular.js中使用令牌管理身份驗證?

[英]How to manage authentication with token in angular.js?

大家好,我創建了一個帶令牌身份驗證的RESTful API(Rails 4 + Devise),我也用gem(rack-cors)管理CORS實現,但是現在我想將該API與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: 'developer.jimenez@gmail.com', password: '12345678'});
  };

}]);

到目前為止,我還沒有實現問題。 我的問題是不知道如何管理退回我工廠的令牌。

使用angular.js管理用戶令牌並在angular.js的差異控制器中驗證用戶的良好實踐是什么?

這是我的第一個帶有令牌身份驗證的應用程序。 意見非常感謝!

一種常見的做法是將安全邏輯放入服務中,並使用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;
            }
        };
    }]);

引導應用程序時,請不要忘記添加攔截器

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

現在,令牌將在每個http請求上設置,如果失敗,您該怎么做才由您決定。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM