How to skip angularjs interceptor for an HTTP request?
Asked Answered
Q

4

5

I have an angularjs app, in which I have an interceptor that adds the authorization token to the header of each request.

However, somewhere in the application I need to use and external API where the interceptor ruins it, because it adds this authorization header which is not acceptable by this external API provider. How can I make angularjs HTTP skip the interceptor, only on this one specific case?

The interceptor code is below:

app.factory('authInterceptorService', ['$q', '$injector', '$location', 'localStorageService', function ($q, $injector, $location, localStorageService) {
    var authInterceptorServiceFactory = {};
    var $http;

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            //console.log("token: " + authData.token.substring(0, 10));
            //console.log("user: " + authData.userName);
            config.headers.Authorization = 'Bearer ' + authData.token;
        }
        return config;
    }

    var _responseError = function (rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            authService.refreshToken().then(function (response) {
                _retryHttpRequest(rejection.config, deferred);
            }, function () {
                authService.logOut();
                $location.path('/login');
                deferred.reject(rejection);
            });
        } else {
            deferred.reject(rejection);
        }
        return deferred.promise;
    }

    var _retryHttpRequest = function (config, deferred) {
        console.log('retrying');
        $http = $http || $injector.get('$http');
        $http(config).then(function (response) {
            deferred.resolve(response);
            //console.log("success:" +response);
        }, function (response) {
            deferred.reject(response);
            //console.log("error:" + response);
        });
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;

    return authInterceptorServiceFactory;
}]);
Quite answered 6/6, 2016 at 3:48 Comment(2)
add logic to skip adding of auth header based on config.urlNephew
I think you should take a loot at this post: #23696702Epithet
L
10

Easy

$http.get("url" , {noAuth : true}).then(success(),error());

In the Interceptor

  var _request = function (config) {

    config.headers = config.headers || {};

    var authData = localStorageService.get('authorizationData');
    if (authData && !config.noAuth) {
        //console.log("token: " + authData.token.substring(0, 10));
        //console.log("user: " + authData.userName);
        config.headers.Authorization = 'Bearer ' + authData.token;
    }
    return config;
}
Lungan answered 6/6, 2016 at 5:35 Comment(0)
R
5

Simple. Change this line

if (authData) {

to

if (authData && !config.headers.hasOwnProperty('Authorization')) {

And for any request where you do not want the header applied, use

$http({
    headers { Authorization: null },
    // and the rest
})
Ramshackle answered 6/6, 2016 at 4:34 Comment(0)
B
5

Write like this :-

   var _request = function (config) {
    if (config.url.indexOf('yourExternalApiUrl') > -1) {
         return config;
    } else {
         config.headers = config.headers || {};
         var authData = localStorageService.get('authorizationData');
         if (authData) {
             //console.log("token: " + authData.token.substring(0, 10));
             //console.log("user: " + authData.userName);
             config.headers.Authorization = 'Bearer ' + authData.token;
         }
    return config;
    }        
}

For more details you can see : http://www.codemosquitoes.com/2016/06/using-angularjs-interceptors-with-http.html

Bandolier answered 8/6, 2016 at 6:22 Comment(0)
C
1

If you are looking for the auth0 interceptor:

export class InterceptorService implements HttpInterceptor {
    constructor(private auth: AuthService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        var allow = ['/assets/i18n/de.json', '/assets/i18n/en.json'];

        if (allow.includes(req.url)) {
            const noToken = req.clone();
            return next.handle(noToken);
        }
        return this.auth.getTokenSilently$().pipe(
            mergeMap(token => {
                const tokenReq = req.clone({
                    setHeaders: { Authorization: `Bearer ${token}` }
                });
                return next.handle(tokenReq);
            }),
            catchError(err => throwError(err))
        );
    }
}
Chaos answered 2/6, 2020 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.