我有一个基本的
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,从而规避角度检查器.