javascript 如果未通过身份验证,则重定向所有路由以登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26145871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect on all routes to login if not authenticated
提问by sturoid
How can I redirect to the login page if someone tries to hit any other route when they are not authenticated? Is there a "best" way to do this in AngularJS?
如果有人在未通过身份验证时尝试访问任何其他路由,我如何重定向到登录页面?在 AngularJS 中是否有“最佳”方法可以做到这一点?
Seems like a common problem but I can't seem to find a way to do this. Thank you in advance for your help.
似乎是一个常见问题,但我似乎无法找到一种方法来做到这一点。预先感谢您的帮助。
回答by Rorschach120
The best way to do this is to set up a '$routeChangeStart' listener which checks an 'authProvider' service function to verify that there is a user logged in. In our 'app.js' or in a separate file:
最好的方法是设置一个“$routeChangeStart”侦听器,它检查“authProvider”服务功能以验证是否有用户登录。在我们的“app.js”或单独的文件中:
angular.module('myApp')
.run(['$rootScope', '$location', 'authProvider', function ($rootScope, $location, authProvider) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!authProvider.isLoggedIn()) {
console.log('DENY : Redirecting to Login');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
}
});
}])
Then for our 'authProvider' service:
然后对于我们的“authProvider”服务:
angular.module('myApp')
.factory('authProvider', function() {
var user;
return {
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
};
});
This solution was created from an answer hereon stack overflow.
此解决方案是根据此处有关堆栈溢出的答案创建的。
Thank you @MohammadAwwaad
谢谢@MohammadAwwaad
回答by trysis
I am doing this a different way now, with Node.js & Express & the passport
module, but before that, when I was using PHP, I did it with several Angular modules. I had an outside module on my <html>
tag with ng-app
, then ng-controller
s at certain tags, like <body>
& certain <div>
s. In one of these ng-controller
s, I had an authentication function, then I had an ng-if
for login, logout, etc. If the user is not logged in, I hid the current page and ng-include
d the appropriate page. Otherwise, I ng-include
d the current page.
我现在以不同的方式使用 Node.js & Express &passport
模块,但在此之前,当我使用 PHP 时,我使用了几个 Angular 模块。我的<html>
标签上有一个外部模块,带有ng-app
,然后ng-controller
是某些标签,例如<body>
& 某些<div>
s。其中之一ng-controller
,我有一个认证功能,然后我有一个ng-if
用于登录,注销等。如果用户没有登录,我隐藏当前页面并ng-include
d适当的页面。否则,我会ng-include
访问当前页面。
That was probably not the best solution, but I didn't want to use third-party modules. If you get confused or have any questions (I know I was pretty confused) just ask.
这可能不是最好的解决方案,但我不想使用第三方模块。如果您感到困惑或有任何问题(我知道我很困惑),请提出。