[英]Redirect on all routes to login if not authenticated
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. 预先感谢您的帮助。
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 here on stack overflow. 该解决方案是从一个答案创建这里对堆栈溢出。
Thank you @MohammadAwwaad 谢谢@MohammadAwwaad
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. 我现在以不同的方式使用Node.js&Express和passport
模块,但在此之前,当我使用PHP时,我使用了几个Angular模块。 I had an outside module on my <html>
tag with ng-app
, then ng-controller
s at certain tags, like <body>
& certain <div>
s. 我的<html>
标签上有一个带有ng-app
的外部模块,然后是某些标签的ng-controller
,比如<body>
和某些<div>
。 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. 在其中一个ng-controller
,我有一个认证功能,然后我有一个ng-if
用于登录,注销等。如果用户没有登录,我隐藏了当前页面并且ng-include
d相应的页面。 Otherwise, I ng-include
d the current page. 否则,我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. 如果你感到困惑或有任何疑问(我知道我很困惑),请问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.