How to override header Token with AngularJS - angularjs

I have problem to override header token with AngularJS becauase already set with AuthInterceptor.
app.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if (localStorage.getItem("token")!=='') {
config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
}
return config;
},
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
I would access another third party URL where using another Token,but always failed, because Token back to current Token in localStorage. I have used TransformRequest, but not work too, what is best practice to solve the problem?

You could check that the URL in the intercepted request is a URL that you want to pass an authorization token. For instance, if the URL to your own API always starts with https://api.myapp.com, you could do it like this:
app.factory('authInterceptor', function ($rootScope, $q, $window) {
var urlForAuthorization = 'https://api.myapp.com';
return {
request: function (config) {
config.headers = config.headers || {};
if (config.url.startsWith(urlForAuthorization)
&& localStorage.getItem("token") !== '') {
config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
}
return config;
}
};
});

Related

How to conditionally bypass request interceptor in AngularJs

I'm having trouble bypassing my auth interceptor:
request: function (config) {
if (config.headers["NoAuth2"] !== null) return config;
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
} else {
var authService = $injector.get('authService');
authService.logOut();
$location.path('/login');
}
return config;
}
Ideally, when the headers have NoAuth2 present in it's collection, I'd like to bypass adding the token and just return the config via something like:
$http.post(config.url + "pubrequest", request, { headers : {NoAuth2 : 1}})
From my controller.
However, I can't seem to get it to work despite several SOE examples on it, any ideas?

angular auth interceptor on selected request

I have written an auth interceptor that adds auth token to the request and handles auth errors if the user is not logged in.
var storeApp = angular.module('storeApp');
storeApp.factory('authInterceptor', function ($q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response.status === 401 || response.data.error === 'token_not_provided') {
console.log('auth error');
}
return $q.reject(response);
}
};
});
storeApp.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('authInterceptor');
});
The issue is the auth interceptor is added to every request, regardless the request requires authentication or not. What is the best way to create an auth interceptor that only intercepts when the route requires authentication?
You need the filter out the requests you want in the authInterceptor factory methods
['/whatever/1', '/whatever/2', '/whatever/3'].forEach(function(value){
if (response.config.url.startsWith(value)) {
// do something
}
})
return response;

How can I make $http with authentication?

I have make a POST request to an API and they have basic authentication, how can I tell angular $http POST service to pass my credential while making the post requestion?
You can add auth interceptor as follows
angular.module('interceptors.authInterceptor',[])
.factory('authInterceptor', ['$q', function ( $q) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers['Authorization'] = 'Bearer ' + YOUR_AUTH_TOKEN;
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function(rejection) {
}
};
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}]);

angular multiple interceptors in app.config

in my angular app, I want to add informations to all calls to an external API.
To do so, I use interceptors that I call from within app.config.
app.config(['$httpProvider', ... , function($httpProvider, ...){
$httpProvider.interceptors.push('globalInterceptorService');
$httpProvider.interceptors.push('authInterceptorService');
}]);
It works fine when I only use one interceptor. But when I use 2 of them (as in the example above) the action of one gets overridden by the other.
Any idea about how to deal with multiple interceptors? Maybe is it recommended to have only 1? Any help is much appreciate.
Interceptor 1 :
function globalInterceptorService ($q, localStorageService) {
var service = {};
var _request = function (config) {
config.headers = config.headers || {};
var AreaId = localStorageService.get('AreaId');
if (AreaId) {
config.headers.AreaId = 'AreaId ' + AreaId;
}
return config;
};
service.request = _request;
return service;
}
Interceptor 2 :
function authInterceptorService ($q, $location, localStorageService) {
var service = {};
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
};
service.request = _request;
return service;
}
I think you should push the function, not its string name.
function globalInterceptorService($q, localStorageService){...}
$httpProvider.interceptors.push(globalInterceptorService);
example: http://jsfiddle.net/aartek/tbhobfbu
Or
function globalInterceptorService($q, localStorageService){...}
$provide.factory('globalInterceptorService',globalInterceptorService)
$httpProvider.interceptors.push('globalInterceptorService');
example: http://jsfiddle.net/aartek/tbhobfbu/2/
It's well described in the documentation

AngularJS $http request authorization header changing token

I have this $http call after a user has logged in that get's the users' details. When the user logs in I store the token in user.token which looks like this:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1laWQiOiIzZGMwM2FiOC0wZGFiLTQ1ZGYtYjEwNS03Y2VmNDA4ZjQ4YWQiLCJ1bmlxdWVfbmFtZSI6InIzcGxpY2EiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL2FjY2Vzc2NvbnRyb2xzZXJ2aWNlLzIwMTAvMDcvY2xhaW1zL2lkZW50aXR5cHJvdmlkZXIiOiJBU1AuTkVUIElkZW50aXR5IiwiQXNwTmV0LklkZW50aXR5LlNlY3VyaXR5U3RhbXAiOiI4NGIyMjMzMi1jOTkyLTQ1YjItYWI0Yi1mYzU1YzkzYWU3NjIiLCJyb2xlIjoiQWRtaW5pc3RyYXRvciIsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTgxMjciLCJhdWQiOiJkM2U3OWM4MS0xNjNmLTQwMTMtODA2NC0zMDc1OTBhOWMwYmYiLCJleHAiOjE0MzMyNzc2NDIsIm5iZiI6MTQzMzE5MTI0Mn0.erNou7AjihJrp2glS89zNYYFc65mREscGwl45wVUSYA
I then take this token and pass it to an $http call like this:
$http.get('api/users', { headers: { 'Authorization': 'Bearer ' + user.token }, params: { username: model.userName } });
But in fiddler if I examine this call, it changes my token. The request in fiddler looks like this:
Authorization: Bearer cF9xV4hw3psCq2of-wRDn-cRE_IifwzCYyoS-c5Njdk4dGu7EGGQ8Bl_XOr8uEGMAFkxR0paqfCI4Aq17VWP6BDxMZN2Nkk7WIfPLVrilKkMybmGxbOqAKqwl3F1qnEvtlvdgQtdpAqgR6-s1oFU0QemRVaQiyOPbmJwEyfh5mYrNVLuZniPPCvpZvOKKBSpinpCY-vNINI3SYvbZyVpRza18aFJfXy-JgUSN3YZBmg1T4JFjMucCueqAWlulGaDGRc8hAXp7RYnxeUtDO7yOhPzQehjVVxl59Lz461DpsXcZjuEILhlFXbyC4yn24DHIFfLs0_x9DCZwodXaaAwoCmRI_vx8yLpjfoPcmnOR_20lLlWp0pOODOqoKSRxZldnRZO8pbilo_AcYHSCQlyeMPOevvO1bP8yggGdCe_LVQiTNJgzhMccKRcziZqZjPCMw0Kz_OLkR5w2ayS5JTdfA
which is not the token that I passed. Does anyone know why this might be happening?
As Kevin rightly said, I was setting it on my http interceptor. It looked like this:
.factory('AuthInterceptorService', ['$rootScope', '$q', '$location', function ($rootScope, $q, $location) {
// Function to handle a request
var request = function (config) {
// Get the current user
var user = $rootScope.user;
// Get the current headers or an empty object
config.headers = config.headers || {};
// If we have a user
if (user && user.token) {
// Then set the authorization header
config.headers.Authorization = 'Bearer ' + user.token;
}
// Return our config
return config;
};
// Function to handle errors
var responseError = function (rejection) {
// If we have unauthorized access
if (rejection.status === 401) {
// Redirect to our login page
$location.path('/account/login');
}
// Return our rejected promise
return $q.reject(rejection);
};
return {
request: request,
responseError: responseError
};
}])
to fix the issue I just simply put an if statement checking to see if the Authorization header had already been set like this:
.factory('AuthInterceptorService', ['$rootScope', '$q', '$location', function ($rootScope, $q, $location) {
// Function to handle a request
var request = function (config) {
// Get the current user
var user = $rootScope.user;
// Get the current headers or an empty object
config.headers = config.headers || {};
// If we have a user
if (user && user.token) {
// If we don't already have the authorization header set
if (!config.headers.Authorization) {
// Then set the authorization header
config.headers.Authorization = 'Bearer ' + user.token;
}
}
// Return our config
return config;
};
// Function to handle errors
var responseError = function (rejection) {
// If we have unauthorized access
if (rejection.status === 401) {
// Redirect to our login page
$location.path('/account/login');
}
// Return our rejected promise
return $q.reject(rejection);
};
return {
request: request,
responseError: responseError
};
}])
simples :)

Resources