【问题标题】:how to develop angularjs interceptor to control session如何开发angularjs拦截器来控制会话
【发布时间】:2016-06-02 05:52:15
【问题描述】:

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

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

【问题讨论】:

    标签: angularjs angular-http-interceptors


    【解决方案1】:

    如果你想要一个基于令牌的控件,你可以这样做:

    你的拦截器:

    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. 服务器在每个请求中,从传入的请求中提取token,通过token查找用户标识,获取用户信息进行认证/授权。
    7. 如果令牌过期,服务器会生成另一个令牌并将其发送回客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-29
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多