Afflatus
Afflatus

Reputation: 943

401 (Unauthorized) Error on Get method

I am creating a simple login application using HTTP Auth Interceptor Module.

in my LoginController I have:

angular.module('Authentication')
.controller('LoginController',
['$scope', '$rootScope', '$location', 'AuthenticationService',
function ($scope, $rootScope, $location, AuthenticationService) {
    // reset login status
    AuthenticationService.ClearCredentials();

    $scope.login = function () {
        $scope.dataLoading = true;
        AuthenticationService.Login($scope.username, $scope.password, function (response) {
            if (response.success) {
                AuthenticationService.SetCredentials($scope.username, $scope.password);
                $location.path('/');
            } else {
                $scope.error = response.message;
                $scope.dataLoading = false;
            }
        });

    };
}]);

and following is the simple service for it:

angular.module('Authentication')

.factory('AuthenticationService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope, $timeout, $scope) {
    var service = {};

    service.Login = function ($scope, username, password, callback) {

        $http
            .get('http://Foo.com/api/Login', 
                        { username: username, password: password } , {withCredentials: true}).
                        then(function (response) {
                                console.log('logged in successfully');
                                callback(response);
                        }, function (error) {
                                console.log('Username or password is incorrect');
                        });
    };

    service.SetCredentials = function (username, password) {
        var authdata = Base64.encode(username + ':' + password);

        $rootScope.globals = {
            currentUser: {
                username: username,
                authdata: authdata
            }
        };

        $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; 
        $http.defaults.headers.common['Content-Type'] = 'application/json'
        $cookieStore.put('globals', $rootScope.globals);
    };

    service.ClearCredentials = function () {
        $rootScope.globals = {};
        $cookieStore.remove('globals');
        $http.defaults.headers.common.Authorization = 'Basic ';
    };

    return service;
}])

This is my login page: enter image description here

as I try to test this in browser, instead of successful login or even receiving an error, I get this popup: enter image description here

what I don't get is that why the credential passed from the login form is not taken into account. and how can I get rid of this popup. as I cancel this popup, again instead of getting the error for http request, in console I get 401 (Unauthorized) Error. What am I missing?

I also ran in in Emulator and instead of getting any error, the application stays on loading part.

Upvotes: 2

Views: 8409

Answers (2)

Siavosh Tehrani
Siavosh Tehrani

Reputation: 135

  1. Change your URL to something like

    .get('https://username:password@Foo.com/api/Login',...
    
  2. use the following sample to handle 401 error:

    .config(['$httpProvider', function($httpProvider) {
         $httpProvider.defaults.useXDomain = true;
         $httpProvider.defaults.withCredentials = true;
         $httpProvider.interceptors.push(['$q', function ($q) {
           return {
             'responseError': function (rejection) {
               if (rejection.status === 401) {
                 console.log('Got a 401');
               }
               return $q.reject(rejection)
             }
           }
         }]) 
     }])
    

Upvotes: 3

thatzprem
thatzprem

Reputation: 4767

Here is the working code snippet. Just copy paste from here.

routerApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = true;
    $httpProvider.interceptors.push(['$q', function ($q) {
      return {
        'responseError': function (rejection) {
          if (rejection.status === 401) {
            window.console.log('Got a 401');
          }
          return $q.reject(rejection);
        }
      };
      }]);
}]);

Upvotes: 0

Related Questions