【问题标题】:Prevent AngularJS Controller call if unauthenticated如果未经身份验证,防止 AngularJS 控制器调用
【发布时间】:2013-08-03 15:21:17
【问题描述】:

我有一个关于路由更改的基本身份验证检查,它只是检查 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');
        }
    })
})

【问题讨论】:

标签: angularjs


【解决方案1】:

我建议您应该在服务器端检查身份验证并在客户端返回适当的消息

以下是网址帮助 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);

【讨论】:

    猜你喜欢
    • 2016-07-02
    • 2023-04-10
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2013-06-17
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多