加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:根据用户是否授权,用angularjs保护路由?

发布时间:2020-12-17 09:41:19 所属栏目:安全 来源:网络整理
导读:我刚刚开始使用我正在开发的AngularJS应用程序,一切顺利,但是我需要一种保护路由的方式,以便用户不会被允许进入该路由,如果没有登录,我明白重要性在服务端也保护,我会照顾这个. 我已经找到了一些保护客户端的方法,一个似乎使用以下 $scope.$watch( function(
我刚刚开始使用我正在开发的AngularJS应用程序,一切顺利,但是我需要一种保护路由的方式,以便用户不会被允许进入该路由,如果没有登录,我明白重要性在服务端也保护,我会照顾这个.

我已经找到了一些保护客户端的方法,一个似乎使用以下

$scope.$watch(
    function() {
        return $location.path();
    },function(newValue,oldValue) {
        if ($scope.loggedIn == false && newValue != '/login') {
            $location.path('/login');
        }
    }
);

我在哪里需要把它放在app.js的.run中?

而我发现的另一种方法是使用一个指令并使用on-routechagestart

信息在这里http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

我真的有兴趣在任何人的帮助和反馈推荐的方式.

使用解析可以帮助您:(代码未测试)
angular.module('app' []).config(function($routeProvider){
    $routeProvider
        .when('/needsauthorisation',{
            //config for controller and template
            resolve : {
                //This function is injected with the AuthService where you'll put your authentication logic
                'auth' : function(AuthService){
                    return AuthService.authenticate();
                }
            }
        });
}).run(function($rootScope,$location){
    //If the route change failed due to authentication error,redirect them out
    $rootScope.$on('$routeChangeError',function(event,current,previous,rejection){
        if(rejection === 'Not Authenticated'){
            $location.path('/');
        }
    })
}).factory('AuthService',function($q){
    return {
        authenticate : function(){
            //Authentication logic here
            if(isAuthenticated){
                //If authenticated,return anything you want,probably a user object
                return true;
            } else {
                //Else send a rejection
                return $q.reject('Not Authenticated');
            }
        }
    }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读