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://andreareginato.github.io/oauth-ng/?
$scope.$on('oauth:login', function(event, token) {
console.log('Authorized third party app with token', token.access_token);
});
$scope.$on('oauth:logout', function(event) {
console.log('The user has signed out');
});
$scope.$on('oauth:loggedOut', function(event) {
console.log('The user is not signed in');
});
$scope.$on('oauth:denied', function(event) {
console.log('The user did not authorize the third party app');
});
$scope.$on('oauth:expired', function(event) {
console.log('The access token is expired. Please refresh.');
});
$scope.$on('oauth:profile', function(profile) {
console.log('User profile data retrieved: ', profile);
});
Thanks,
Simon
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.