Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了认证 – 如何使用AngularJS ngView隐藏模板以供未经授权的用户?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个基本的 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,从而规避角度检查器.

大佬总结

以上是大佬教程为你收集整理的认证 – 如何使用AngularJS ngView隐藏模板以供未经授权的用户?全部内容,希望文章能够帮你解决认证 – 如何使用AngularJS ngView隐藏模板以供未经授权的用户?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。