Angularjs

Require Authentication For Certain Routes With UI-Router In AngularJS

Posted by Weston Ganger on July 25, 2015

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:


Posted in Angular and Tagged with angularjs authentication ui-router 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts