如何开发angularjs拦截器来控制会话

时间:2016-06-01 16:41:23

标签: angularjs angular-http-interceptors

我是一名学生,最近正在研究angularJS拦截器,并尝试开发一个控制会话管理。我是平均堆栈开发的新手,需要帮助。 有没有人有一个angularJS会话管理的工作示例?

非常感谢您的帮助和时间。

1 个答案:

答案 0 :(得分:3)

如果您想要基于令牌的控件,您可以执行以下操作:

你的拦截器:

angular.module('yourApp').factory('YourHttpInterceptor', ['$q', '$window',
function($q, $window) {
    return {        
        'request': function(config) {
            config.headers = config.headers || {};

            // If you have a token in local storage for example: 
            if ($window.localStorage.token) {
                // Add the token to "Authorization" header in every request
                config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
                // In your server you can check if the token is valid and if it's not,
                // in responseError method you can take some action
            }


            // Handle something else

            return config;
        },       

        // Optional method
        'requestError': function(rejection) {
            // do something on request error 

            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        },        

        // Optional method        
        'response': function(response) {
            // do something on response success
            return response;
        },

        // optional method 
        'responseError': function(rejection) {
            // Here you can do something in response error, like handle errors, present error messages etc.

            if(rejection.status === 401) { // Unauthorized 
                // do something
            }

            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
}]);

在你的模块配置中注册拦截器:

angular.module('yourApp', []).config(function($httpProvider) {
    $httpProvider.interceptors.push('YourHttpInterceptor');
}

正如您在this post中看到的,基于令牌的身份验证遵循以下步骤(几乎总是):

  1. 客户端将其凭据(用户名和密码)发送到服务器。
  2. 服务器对它们进行身份验证并生成具有过期日期的令牌。
  3. 服务器将先前生成的令牌存储在具有用户标识符的某个存储中,例如数据库或内存中的映射。
  4. 服务器将生成的令牌发送给客户端。
  5. 在每个请求中,客户端都会将令牌发送到服务器。
  6. 服务器在每个请求中从传入请求中提取令牌,使用令牌查找用户标识符以获取用于执行身份验证/授权的用户信息。
  7. 如果令牌过期,服务器会生成另一个令牌并将其发送回客户端。
相关问题