![]()
Role-based authentication ensures that only users with specific roles can access certain routes. This is achieved using AngularJS’s $routeProvider and $routeChangeStart event.
1️⃣ Steps to Implement Role-Based Authentication
Step 1: Define Routes with Role-Based Restrictions
In app.config(), specify which roles are allowed for each route using resolve.
app.config(function($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl',
resolve: {
auth: function(AuthService, $q, $location) {
return AuthService.checkAccess(['admin', 'editor']).catch(function() {
$location.path('/unauthorized'); // Redirect unauthorized users
return $q.reject('Unauthorized');
});
}
}
})
.when('/user', {
templateUrl: 'user.html',
controller: 'UserCtrl',
resolve: {
auth: function(AuthService, $q, $location) {
return AuthService.checkAccess(['user', 'admin']).catch(function() {
$location.path('/unauthorized');
return $q.reject('Unauthorized');
});
}
}
})
.otherwise({
redirectTo: '/'
});
});
Explanation:
/dashboardis accessible only toadminandeditor./useris accessible touserandadmin.- If unauthorized, the user is redirected to
/unauthorized.
Step 2: Create an Authentication Service
A service to manage user roles and check access permissions.
app.service('AuthService', function($q) {
var user = {
isAuthenticated: true,
role: 'editor' // Change this to test different roles
};
this.getUser = function() {
return user;
};
this.checkAccess = function(allowedRoles) {
var deferred = $q.defer();
if (user.isAuthenticated && allowedRoles.includes(user.role)) {
deferred.resolve(true);
} else {
deferred.reject('Unauthorized');
}
return deferred.promise;
};
});
Explanation:
getUser()returns the current user details.checkAccess(allowedRoles)checks if the user’s role is allowed for the route.
Step 3: Protect Routes with $routeChangeStart
Even though resolve handles route restrictions, using $routeChangeStart ensures users can’t manually bypass authentication.
app.run(function($rootScope, $location, AuthService) {
$rootScope.$on('$routeChangeStart', function(event, next) {
if (next.resolve && next.resolve.auth) {
AuthService.checkAccess(next.resolve.auth.allowedRoles).catch(function() {
event.preventDefault();
$location.path('/unauthorized'); // Redirect unauthorized users
});
}
});
});
Explanation:
- This ensures unauthorized users cannot navigate manually to protected routes.
event.preventDefault()stops the route change if access is denied.
Step 4: Display Role-Based UI Elements
In your HTML, show/hide elements based on user roles.
<div ng-show="user.role === 'admin'">
<a href="#/dashboard">Admin Dashboard</a>
</div>
<div ng-show="user.role === 'user'">
<a href="#/user">User Profile</a>
</div>
This dynamically hides/show links based on the logged-in user’s role.
