Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS promise catch 401

I am using a very basic angularJS code for a user login like this:

[...]
this.login = function(email, password) {
    promise = $http.post('/login',
            {
                'email': email,
                'password': password
            });
    promise.then(function(response){
            console.log("success");
        }).catch(function(response){
            console.log("catch");
        }).finally(function(response){
            console.log("finally");
        });
    return promise;
};
[...]

When the REST API generates an response with code 200, then the client console will log success finally and the user is logged in.
When the server generates a response with a 403 or 500 code, the console will print out catch finally.

But when the response will be with a 401, angular does not print out anything. The console will stay empty, only with the POST http://127.0.0.1/login 401 (Unauthorized) hint. But no success or catch as output. And no finally neither.

In my project, 403 will be catched globally with a $rootScope.$on('event:auth-forbidden', function(r) {...});. That's why the REST Server will only throw 404 when something is not found, 403 when the user has no permission and/or is not logged in and 401 only if the login failed.

So how can I catch a 401 on $http?
Isn't the .then promise only for return 200 and the .catch for every other return != 200?

I am using angularJS v1.6.4 with angular-http-auth v1.5.0.

like image 642
christopher2007 Avatar asked Oct 30 '22 02:10

christopher2007


1 Answers

The problem is that angular-http-auth module intercepts the responses with status 401 or 403:

The $http interceptor does the following: the configuration object (this is the requested URL, payload and parameters) of every HTTP 401 response is buffered and everytime it happens, the event:auth-loginRequired message is broadcasted from $rootScope.

To disable the 401 interceptor set ignoreAuthModule: true:

Sometimes you might not want the interceptor to intercept a request even if one returns 401 or 403. In a case like this you can add ignoreAuthModule: true to the request config.

The module creates a new promise in pending state for 401 status. The response is buffered and you have a chance to call authService.loginConfirmed() or authService.loginCancelled() functions. The first one retries all the requests previously failed due to HTTP 401 response. When the second one cancels all pending requests previously failed and buffered due to HTTP 401 response.

Docs

like image 73
alexmac Avatar answered Nov 11 '22 13:11

alexmac