In this post, I would like to show a way of restricting some client routes with UI-Router. There are many ways you can solve it, here I will show you a simpler and a more complex one. This code will give you an idea of how it works. Let’s say we have a parent route which all sub routes are using as their parent root and a sample route. This code is for both, the simpler and the more complex one the same.

A simpler scenario

In this simpler solution, we just want to check if a user is logged in or not, for that, we will extend our sample route with this grantAccessTo field

On state change, we now have to check, if the user is logged in. If yes, he or she can proceed, otherwise we will redirect the user to the login page. I assume that the UserDetails is tracking if a user is logged in or not.

With this, we can easily redirect a user if he or she is not logged in.

A more complex scenario

In this more complex solution, we want also check if a user is in specific role or group. For that, lets extend the above example and lets restrict our sample route to admins only.

Then we will have again check on state change if the user is what we expect. We will introduce a new service called authorization.

As in the comment above, if the user was not resolved in that state, we will do the check when the state is resolved. To reduce code, we put it into the parent state.

Here are ways of how you could have done the UserDetails and authorization services (this is not tested, it should just give an idea of how this could work).


Hide Show elements on UI

You can also hide or show something specifically in a view, when we do not want to restrict the whole route, we could then also do something like this in the controller and UI:


The above code is not tested.. and I am assuming that we return roles/groups within the UserDetails object. But it should give an idea of how it can work.


Restrict client routes in Angular with UI-Router
Tagged on:     

One thought on “Restrict client routes in Angular with UI-Router

  • November 5, 2015 at 2:55 pm

    Your article really fits what I am searching for. Trying to implement the “role authorization” part it into an upcoming Angular app.


Leave a Reply


Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: