我对路由更改进行了基本的身份验证检查,只检查是否存在SessionStorage密钥/ val。但是,我注意到如果未经身份验证的用户导航到禁止页面,其控制器包含AJAX调用,则即使禁用了禁用页面而用户被重定向到登录,AJAX调用仍会在后台进行。为了解决这个问题,我在每个控制器中添加了相同的身份验证检查。这变得有点乏味,我想知道是否有更好的方法,或者我可以在控制器的方法运行之前全局检查身份验证。这是路线变更的auth功能:
app.run(function ($rootScope, $location, authenticationService) {
$rootScope.clearAlerts = function(){
$rootScope.alerts = []
}
$rootScope.credentials = {
username: "",
password: ""
};
$rootScope.goto = function(url){
$location.path(url);
}
$rootScope.authenticated = authenticationService.isLoggedIn()
$rootScope.logOut = function () {
authenticationService.logOut();
}
var publicRoutes = ['/login'];
$rootScope.$on('$routeChangeStart', function (event, next, current) {
$rootScope.credentials.from = $rootScope.desiredPath || '/login'
$rootScope.authenticated = authenticationService.isLoggedIn();
if (!_(publicRoutes).contains($location.path()) && !$rootScope.authenticated) {
$rootScope.desiredPath = $location.path();
$location.path('/login');
}
})
})
答案 0 :(得分:2)
我建议您检查服务器端的身份验证并在客户端返回相应的消息
以下是网址帮助 http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application
并在客户端编写全局处理程序以检查它
以下是示例代码:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "./index.html";
return;
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);