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

认证 – 如何使用AngularJS ngView隐藏模板以供未经授权的用户?

发布时间:2020-12-17 07:36:58 所属栏目:安全 来源:网络整理
导读:我有一个基本的 PHP应用程序,其中用户登录存储在HTTP会话中.该应用程序有一个主要模板,如index.html,使用ngView切换子视图,像这样 body ng-controller='MainCtrl' div ng-view/div/body 现在,这个主要的模板可以通过基本的PHP控件进行保护,但是我有一个简单
我有一个基本的 PHP应用程序,其中用户登录存储在HTTP会话中.该应用程序有一个主要模板,如index.html,使用ngView切换子视图,像这样
<body ng-controller='MainCtrl'>
    <div ng-view></div>
</body>

现在,这个主要的模板可以通过基本的PHP控件进行保护,但是我有一个简单的html文件的子模板(即用户列表,添加用户,编辑用户等),根据我的路由设置包含在角度上.

虽然我能够查看是否涉及http服务的请求,但一个用户能够导航到子模板网址并访问它.我如何防止这种情况发生?

我会创建一个这样的服务:
app.factory('routeAuths',[ function() {
  // any path that starts with /template1 will be restricted
  var routeAuths = [{
      path : '/template1.*',access : 'restricted'
  }];
  return {
    get : function(path) {
      //you can expand the matching algorithm for wildcards etc.
      var routeAuth;
      for ( var i = 0; i < routeAuths.length; i += 1) {
        routeAuth = routeAuths[i];
        var routeAuthRegex = new RegExp(routeAuth.path);
        if (routeAuthRegex.test(path)) {
          if (routeAuth.access === 'restricted') {
            return {
              access : 'restricted',path : path
            };
          }
        }
      }
      // you can also make the default 'restricted' and check only for 'allowed'
      return {
        access : 'allowed',path : path
      };
    }
  };
} ]);

并在main / root控制器中收听$locationChangeStart事件:

app.controller('AppController',['$scope','$route','$routeParams','$location','routeAuths',function(scope,route,routeParams,location,routeAuths) {
    scope.route = route;
    scope.routeParams = routeParams;
    scope.location = location;

    scope.routeAuth = {
    };

    scope.$on('$locationChangeStart',function(event,newVal,oldVal) {
      var routeAuth = routeAuths.get(location.path());
      if (routeAuth.access === 'restricted') {
        if (scope.routeAuth.allowed) {
          event.preventDefault();
        }
        else {
          //if the browser navigates with a direct url that is restricted
          //redirect to a default
          location.url('/main');
        }
        scope.routeAuth.restricted = routeAuth;
      }
      else {
        scope.routeAuth.allowed = routeAuth;
        scope.routeAuth.restricted = undefined;
      }
    });

}]);

演示:

> plunker

参考文献:

> angularjs services
> location

更新:

为了完全防止html模板访问,最好在服务器上完成.因为如果您从服务器上的静态文件夹中提供html,用户可以直接访问该文件,例如:root_url / templates / template1.html,从而规避角度检查器.

(编辑:李大同)

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

    推荐文章
      热点阅读