AngularJS:根据用户是否获得授权使用 angularjs 保护路由? [英] AngularJS: Protecting routes with angularjs depending if the user is authorized?
问题描述
我刚刚开始使用我正在开发的 AngularJS
应用程序,一切都很顺利,但我需要一种保护路由的方法,这样用户就不会被允许去那里如果未登录,则路由.我也理解在服务端进行保护的重要性,我会处理这个问题.
I have just started out working with an AngularJS
app I'm developing, everything is going well but I need a way of protecting routes so that a user wouldn't be allowed to go to that route if not logged in. I understand the importance of protecting on the service side also and I will be taking care of this.
我找到了多种保护客户端的方法,其中一种似乎使用了以下方法
I have found a number of ways of protecting the client, one seems to use the following
$scope.$watch(
function() {
return $location.path();
},
function(newValue, oldValue) {
if ($scope.loggedIn == false && newValue != '/login') {
$location.path('/login');
}
}
);
我需要把它放在哪里,在 app.js
的 .run
中?
where do I need to put this, in the .run
in the app.js
?
我发现的另一种方法是使用指令并使用 on - routechagestart
And the other way I have found is using a directive and using an on - routechagestart
信息在这里http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app
我真的很想得到任何人对推荐方式的帮助和反馈.
I would really be interested in anyones help and feedback on the recommended way.
推荐答案
使用解决方案应该可以帮助您:(代码未测试)
Using resolves should help you out here: (code not tested)
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');
}
}
}
});
这篇关于AngularJS:根据用户是否获得授权使用 angularjs 保护路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!