AngularJS - 处理刷新令牌?

时间:2014-04-29 13:52:32

标签: javascript angularjs authentication access-token http-status-code-401

我与AngularJS建立SPA,并与服务(JAVA)进行通信。

当用户发送他的用户名/通行证时,服务会发回两个:访问令牌和刷新令牌。我试图处理:如果我得到状态为401的响应,请发回刷新令牌,然后再次发送您的上一个请求。我尝试使用包含$ http来做到这一点,但是角度并没有让我把它包含在这个拦截器中。有没有办法用我接收的响应参数重新创建原始请求?

类似的东西:

  1. 我得到401
  2. 保存我的请求
  3. 如果我有刷新令牌发送该刷新令牌
  4. 成功重新发送我的请求
  5. 错误重定向到/登录页面

    'use strict';
    
    angular.module('testApp')
        .factory('authentificationFactory', function($rootScope, $q, $window, $location, CONF) {
    
    return {
        request: function(config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            console.log(config);
            $rootScope.lastRequest = config;
            return config;
        },
    
        response: function(response) {
            console.log($rootScope.lastRequest);
            if (response.status === 401) {
                if ($window.sessionStorage.refreshToken) {
    
                    //Save, request new token, send old response
                    //if it fails, go to login
    
                    $location.url('/login');
                } else {
                    $location.url('/login');
                }
            }
            return response || $q.when(response);
        }
    };
    });
    
  6. 奖金问题(主要问题更为重要):有2个移动应用程序也将连接到我的服务,当我从我的网络应用程序登录时,稍后我的移动应用程序,移动应用程序需要新的刷新令牌和我的网络应用程序的刷新令牌不再有效。处理这个问题的最佳选择是什么?

    感谢您的时间, 最好的问候

2 个答案:

答案 0 :(得分:11)

看看这个:https://github.com/witoldsz/angular-http-auth

他使用缓冲区在身份验证后重播请求。

答案 1 :(得分:5)

我强烈建议反对在像Angular这样的SPA上发送和存储刷新令牌。

如果您正在使用会话存储或本地存储,那么您正在打开一个机会窗口,可以通过XSS攻击或用户无人看管来捕获此refreshToken。

有关详细信息,请参阅this articlethis question