我正在使用HTTP Auth Interceptor Module创建一个简单的登录应用程序。
在我的LoginController中我有:
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;
}
});
};
}]);
以下是它的简单服务:
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;
}])
当我尝试在浏览器中测试它,而不是成功登录甚至收到错误时,我得到这个弹出窗口:
我没有得到的是为什么不会考虑从登录表单传递的凭证。以及如何摆脱这个弹出窗口。 当我取消此弹出窗口时,再次取代获取http请求的错误,在控制台中我得到401(未授权)错误。 我错过了什么?
我也在Emulator中运行,而不是出现任何错误,应用程序仍然在加载部分。
答案 0 :(得分:2)
1-将您的网址更改为
.get('https://username:password@Foo.com/api/Login',...
2-使用以下示例处理401错误:
.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)
}
}
}])
}])
答案 1 :(得分:0)
以下是工作代码段。只需从此处复制粘贴。
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);
}
};
}]);
}]);