Domanda

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

È stato utile?

Soluzione

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

He uses a buffer to replay the requests after authentication.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top