In AngularJS applications, redirecting users based on their roles is a common requirement, especially for implementing role-based access control (RBAC). This ensures that users can only access specific routes or features based on their roles (e.g., Admin, User, Guest).
In this guide, we will walk through how to implement role-based redirection in AngularJS using UI Router and AngularJS services. The process involves checking the user’s role on route access and redirecting them to the appropriate page if they don’t have the required permissions.
Step 1: Set Up Your AngularJS Application
First, make sure you have AngularJS and UI Router set up in your project. Here’s a basic HTML structure for the app:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS Role-based Redirection</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
</head>
<body ng-app="roleApp">
<div>
<a ui-sref="home">Home</a> |
<a ui-sref="admin">Admin</a> |
<a ui-sref="user">User</a>
</div>
<div ui-view></div>
<script src="app.js"></script>
</body>
</html>
Step 2: Configure the AngularJS Module
In your app.js file, you need to configure the routes using UI Router. We will create different routes for the home, admin, and user views, each having different access controls based on the user’s role.
var app = angular.module('roleApp', ['ui.router']);
// Dummy Authentication Service
app.factory('AuthService', function($q) {
var user = {
role: 'admin' // This can be 'admin', 'user', or 'guest'
};
return {
getUserRole: function() {
return user.role;
},
setUserRole: function(role) {
user.role = role;
}
};
});
app.config(function($stateProvider, $urlRouterProvider) {
// Default route
$urlRouterProvider.otherwise('/home');
// Define States
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('admin', {
url: '/admin',
templateUrl: 'admin.html',
controller: 'AdminController',
resolve: {
// Check if the user has 'admin' role
checkAdmin: function(AuthService, $q, $state) {
if (AuthService.getUserRole() !== 'admin') {
$state.go('home'); // Redirect if the user is not an admin
return $q.reject('Not authorized');
}
return $q.when('Authorized');
}
}
})
.state('user', {
url: '/user',
templateUrl: 'user.html',
controller: 'UserController',
resolve: {
// Check if the user has 'user' role
checkUser: function(AuthService, $q, $state) {
if (AuthService.getUserRole() !== 'user') {
$state.go('home'); // Redirect if the user is not a regular user
return $q.reject('Not authorized');
}
return $q.when('Authorized');
}
}
});
});
Step 3: Define Controllers for Each View
Now, create controllers for each view (home, admin, and user) in your AngularJS application:
- home.html:
<div>
<h1>Home Page</h1>
<p>Welcome to the Home Page!</p>
</div>
- admin.html:
<div>
<h1>Admin Page</h1>
<p>Welcome, Admin! You can manage the system here.</p>
</div>
- user.html:
<div>
<h1>User Page</h1>
<p>Welcome, User! You have access to user-specific content.</p>
</div>
- controllers for the views:
app.controller('HomeController', function($scope) {
$scope.message = "Welcome to the Home Page!";
});
app.controller('AdminController', function($scope) {
$scope.message = "This is the Admin Page!";
});
app.controller('UserController', function($scope) {
$scope.message = "This is the User Page!";
});
Step 4: Implement Role-Based Access Control in the resolve Property
In the above configuration, we used the resolve property for the admin and user states. The resolve block is useful for checking access before the state is loaded. Here, we check if the logged-in user has the appropriate role for the state. If not, we use $state.go() to redirect the user to another state (in this case, the home state).
In the checkAdmin and checkUser methods:
- We use
AuthService.getUserRole()to check the user’s role. - If the user doesn’t have the required role (
adminfor theadminroute,userfor theuserroute), we use$state.go()to redirect them to the home state.
This is a very simple example of role-based redirection in AngularJS.
Step 5: Modify User Role Dynamically (Optional)
If your application allows users to change roles (e.g., logging in as an admin or user), you can modify the role dynamically in your AuthService. Here’s how you can switch roles:
// Sample dynamic role switch
app.controller('RoleController', function($scope, AuthService) {
$scope.setRole = function(role) {
AuthService.setUserRole(role);
};
});
You can use this in your HTML to change the role, for example:
<div>
<button ng-click="setRole('admin')">Login as Admin</button>
<button ng-click="setRole('user')">Login as User</button>
</div>
Step 6: Handle Unauthorized Access Globally (Optional)
You can also handle unauthorized access globally by using $stateChangeStart to intercept route changes and redirect unauthorized users.
app.run(function($rootScope, $state, AuthService) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
// Check if the user is trying to access a restricted state
if (toState.name === 'admin' && AuthService.getUserRole() !== 'admin') {
event.preventDefault();
$state.go('home'); // Redirect to home if unauthorized
}
if (toState.name === 'user' && AuthService.getUserRole() !== 'user') {
event.preventDefault();
$state.go('home'); // Redirect to home if unauthorized
}
});
});
