1

Following is the code I use, I get the Authentication Success Alert if the basic auth succeeds but the else alert "Authentication failed" is never displayed when the credentials are wrong. I do not use any routes and I don't have a need to use interceptors. Is there a way to get the 401 errors without using interceptors?

this.authorize = function(request, callbackFunc) {
  var encodedString = btoa(request.userName + ":" + request.password);
  var basicAuthString = 'Basic ' + encodedString;
  var requestObject = {
    location: '40005'
  };
  var req = {
    method: this.method,
    crossDomain: true,
    url: this.loginURL,
    data: requestObject,
    headers: {
      'Authorization': basicAuthString,
      'Content-Type': 'application/json',
      'Accept': '*/*',
      'apiKey': ''
    }

  };

  $http(req)
    .success(function(response) {
      callbackFunc(response, "success");
    })
    .error(function(response) {
      console.log("Error Received");
      callbackFunc(response, "error");
    });
};

In Controller:

$scope.Login = function() {

  AuthenticationService.authorize($scope.LoginRequest, function(response, responseCode) {
    if (responseCode === "success") {

      alert("Authentication Success");
    } else {
      alert("Authentication Failed");
    }
  });

};
8
  • does console.log("Error Received"); getting printed Commented Feb 28, 2015 at 19:14
  • Nope. It doesn't go there either. Commented Feb 28, 2015 at 19:27
  • 1
    you mean to say error function inside the service doesn't get fire? Commented Feb 28, 2015 at 19:30
  • see here I can do the same thing which is not failing plnkr.co/edit/RlUTqN?p=preview showing "error" message properly Commented Feb 28, 2015 at 19:56
  • I have tried adding an intereceptor too Commented Feb 28, 2015 at 20:03

1 Answer 1

2

As described in the AngularJS documentation for $http, the $http call returns a promise with an error method, which has the code(number) of the status as one of it's parameters. You can check for a 401 status in there:

error(function(data, status, headers, config) {
    if(status === 401){
        // Add your code here
    }
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.