bra*_*orf 12 authentication angularjs
我有一个基本的PHP应用程序,其中用户登录存储在HTTP会话中.该应用程序有一个主模板,比如index.html,可以使用ngView切换子视图,就像这样
<body ng-controller='MainCtrl'>
<div ng-view></div>
</body>
Run Code Online (Sandbox Code Playgroud)
现在,这个主模板可以通过基本的PHP控件保护,但我有子模板(即用户列表,添加用户,编辑用户等),这些是普通的html文件,根据我的路由设置从angular包含.
虽然我能够检查auth与http服务的请求有什么关系,但是一个用户能够导航到子模板URL并访问它.我怎样才能防止这种情况发生?
Liv*_* T. 14
我会创建这样的服务:
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
};
}
};
} ]);
Run Code Online (Sandbox Code Playgroud)
并在主/根控制器中侦听$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;
}
});
}]);
Run Code Online (Sandbox Code Playgroud)
演示:
参考文献:
更新:
为了完全阻止html模板访问,最好在服务器上完成.因为如果你从服务器上的静态文件夹提供html,用户可以直接访问文件ex:root_url/templates/template1.html,从而绕过角度检查器.
| 归档时间: |
|
| 查看次数: |
6596 次 |
| 最近记录: |