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


myApp.config(function($stateProvider, $urlRouterProvider){
  $stateProvider
    .state("forms", {
      url: "/forms",
      templateUrl: "partials/forms.html",
      controller: "FormsListCtrl",
      authenticate: true
    })
    .state("login", {
      url: "/login",
      templateUrl: "partials/login.html",
      controller: "LoginCtrl",
      authenticate: false
    })
    .state("account", {
      url: "/account",
      templateUrl: "partials/account.html",
      controller: "AccountCtrl",
      authenticate: true
    });
  // Send to login if the URL was not found
  $urlRouterProvider.otherwise("/login");
});

Notice the addition of the authenticate property.

Now we need to add a check on route change. We will do this on the $rootScope.


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 - Angular

Date:July 25, 2015