Preventing state transition on ui-router for non authorized users

In the following example I will present how we can restrict access to routers active .state only to authorized users in MVC .NET application.

We want:

  • hide links to specific routes that user is not authorized to
  • prevent state transition on ui-router if user is not authorized

This is easy to achieve because we have session object with user's permissions we can use in Razor view. So we can easily test if the user is authorized and if so display link

Prevent ui-router triggering state transition

We inject Non-URL parameter into ui-router's .state with ui-sref.

Example for passing Non-URL parameters:

.state('testAuthorized', {
 url: '/test',
  params: {
    authorized: 0,
  },
  templateUrl: 'test.html',
  controller: function($scope, $stateParams) {
     $scope.authorized= $stateParams.authorized;
  }
})

and ui-sref="testAuthorized({ authorized: 1 })" will generate the link \test but still pass the authorized parameter in $stateParams.

To prevent access to route we use resolve with promise and if the promise is rejected $stateChangeError is fired otherwise $stateChangeSuccess event is fired.

Example code:

.state('departments', {
    url: '/test',
    templateUrl: 'test.html',
    params: {
        authorized: 0,
    },
    resolve: {
        security: ['$q', '$stateParams', function ($q, $stateParams) {
            if ($stateParams.authorized != 1) {
                return $q.reject("Not Authorized");
            }
        }]
    }
})

To be able to access the route we have to pass authorized parameter to the routers .state. We do that on the Razor view with code

@if (Session.HasPermission(Permissions.TestAuthorized))
{
    <li><a id="test" ui-sref="testAuthorized({authorized: 1})">Authorized view</a></li>
}