Skip to content Skip to sidebar Skip to footer

Angularjs Adding Authorization To Routes

How can I add authorization to AngularJS and ui.router? I'm using the modulg ng-oauth https://github.com/andreareginato/oauth-ng Can I use the following examples from the page http

Solution 1:

You could create some constant roles like this:

.constant('USER_ROLES', {
    ALL: '*', //@unused
    ADMIN: 'ROLE_ADMIN';
    USER: 'ROLE_USER',
    ANONYMOUS: 'ROLE_ANONYMOUS' 
})

Add this custom data/constants to your states:

$stateProvider.state('myapp.admin', {
    url: '/admin',
    .....
    data : {
        authorizedRoles : [USER_ROLES.ADMIN] //Thes
    }
}

So when you authenticate and retrieve these roles from your database you can store this in your user object and session so you can eventually verify this when a route changes...

In your auth service (apart from logging in, logging out etc...) you add the following methods.

isAuthenticated: function () {
    return session.hasSession();
},

isAuthorized: function (authorizedRoles) {
    if (!angular.isArray(authorizedRoles)) {
        authorizedRoles = [authorizedRoles];
    }

    var roles = session.roles();

    var roleIncluded = roles.some(function (role) {
        return (authorizedRoles.indexOf(role) != -1);
    });

    return (session.hasSession() && roleIncluded);
},

So when you change the route in the applications .run block validation occurs and prevention is possible.

$rootScope.$on('$stateChangeStart', function (event, next) {
    if (authService.isAuthenticated()) {
        if (next.data.authorizedRoles === null) {
            handle();
        }
        if (!authService.isAuthorized(next.data.authorizedRoles)) {
            handle();
        }
    } else {
        handle();
    }
}

Ofcourse this is just an example and bear in mind there are other solutions.

Post a Comment for "Angularjs Adding Authorization To Routes"