I'm using Angular v1.2.20 with the Ionic Framework. I have seen many articles and posts about how to handle 401 errors from the server by using an interceptor and pushing it into the $httpProvider.interceptors
array.
For some reason, 401 responses never get caught by the repsonseError
function in my interceptor. The promise I am expecting to reject never rejects and my app just seems to hang (loading:hide
from below never gets called). I can see from my web debugging proxy that a 401 is definitely returned from the server.
My interceptor:
.factory('interceptorService', function($rootScope, $q, Session, AuthorizationHeader) {
var interceptorService = {
request: function(config) {
$rootScope.$broadcast('loading:show');
config.headers['Authentication-Key'] = Session.key();
config.headers['Authentication-Timestamp'] = (new Date().toJSON());
config.headers['Authentication-Account'] = Session.accountName();
if(typeof config.headers['Authorization'] === 'undefined') {
config.headers['Authorization'] = 'Custom-HMAC-SHA512 ' + AuthorizationHeader.buildHashed(config, Session.key());
}
return config || $q.when(config);
},
response: function(response) {
if(response.status === 401) {
console.log('401');
}
$rootScope.$broadcast('loading:hide');
return response || $q.when(response);
},
requestError: function(config) {
$rootScope.$broadcast('loading:hide');
return $q.reject(config);
},
responseError: function(response) {
console.log('response error');
$rootScope.$broadcast('loading:hide');
return $q.reject(response);
}
};
return interceptorService;
})
I can confirm that the interceptor is working as, when I get a 403 back from the server, I can see 'response error' in my console log. Please also note that this happens regardless of HTTP verb used. It's happening with HEAD calls and DELETE calls.
Any help is very much appreciated.
## Edit
It appears that this problem is caused by cordova/phonegap not being able to handle the www-authenticate
header in the 401 response as referenced in this blog post.
If anyone has any ideas on how best to handle that, I'm all ears.
Just remove the WWW-Authenticate header from the response before it gets back to your app. That's what fixed it for me.
handle 401 unauthorized error on windows Phone with Phonegap
Edit: The implementation that was used at my work was done at our F5 (load balancer) since that's where our Basic Authentication occurs.
Here's something I whipped up, that has NOT been tested. You could possibly place this in the Application_EndRequest method in Global.asax.cs file:
if (context.Response.Headers.Contains("WWW-Authenticate"))
context.Response.Headers.Remove("WWW-Authenticate");
来源:https://stackoverflow.com/questions/25730637/angularjs-interceptor-never-catches-401-error