AngularJS - Handling refresh token?

与世无争的帅哥 提交于 2019-11-30 11:24:41

问题


I'm building a SPA with AngularJS with communication to a service (JAVA).

When user sends his username/pass, service sends back both: Acces token and Refresh token. I'm trying to handle: if I get response with status 401, send back refresh token and then send your last request again. I tried to do that with including $http, but angular doesn't let me include it in this interceptor. Is there any way to recreate the original request with this response parameter I'm recieving?

Something like:

  1. I get 401
  2. save my request
  3. if I have a refresh token send that refresh token
  4. on success resend my request
  5. on error redirect to /login page

    '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);
        }
    };
    });
    

Bonus Question (the main question is more important): There are 2 mobile apps that will also connect to my service, and when I log in from my web app, and few moments later from my mobile app, mobile app takes a new refresh token and my web app's refresh token is valid no more. What would be the best option for dealing with that?

Thank you for your time, Best regards


回答1:


Have a look at this: https://github.com/witoldsz/angular-http-auth.

He uses a buffer to replay the requests after authentication.




回答2:


I would strongly advise against sending and storing refresh tokens on SPAs like Angular.

If you are using session storage or local storage, you are opening a window of opportunity for the this refreshToken to be captured, either by a XSS attack, or by the user leaving the computer unattended.

See this article or this question for more info.



来源:https://stackoverflow.com/questions/23366678/angularjs-handling-refresh-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!