Require Authentication For Certain Routes With UI-Router In AngularJS

Posted By Weston Ganger

I wanted a clean way to require authentication for certain routes or pages in my angular app. Heres a really great technique to do that.

First we will edit our routes

angular.module("myApp").run(function ($rootScope, $state, AuthService) {
  $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
    if (toState.authenticate && !AuthService.isAuthenticated()){
      // User isn’t authenticated
      $state.transitionTo("login");
      event.preventDefault(); 
    }
  });
});

That checks to see if the state/route has the authenticate property and then will check your authorization service to see if a user is logged in.

Related External Links:

Article Topic:Software Development - Javascript

Date:July 25, 2015