Redirect on all routes to login if not authenticated

后端 未结 2 1917
青春惊慌失措
青春惊慌失措 2020-12-29 07:45

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?

Seems

相关标签:
2条回答
  • 2020-12-29 08:02

    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:

    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:

    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

    0 讨论(0)
  • 2020-12-29 08:09

    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-controllers at certain tags, like <body> & certain <div>s. In one of these ng-controllers, 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-included the appropriate page. Otherwise, I ng-included the current page.

    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.

    0 讨论(0)
提交回复
热议问题