In AngularJS, protecting routes ensures that only authenticated users can access specific pages. This is typically done by using route guards, authentication services, and route resolvers.
Common Use Cases:
- Restricting access to pages like dashboard, settings, or admin panel.
- Redirecting unauthorized users to login.
- Checking user roles for role-based access control.
2. Setting Up ngRoute for Authentication
Step 1: Configure Routes in $routeProvider
Use resolve
in $routeProvider
to check authentication before allowing access.
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
templateUrl: "views/login.html",
controller: "LoginController"
})
.when("/dashboard", {
templateUrl: "views/dashboard.html",
controller: "DashboardController",
resolve: {
auth: function(AuthService, $location) {
return AuthService.isAuthenticated().then(function(isAuth) {
if (!isAuth) {
$location.path("/login");
}
});
}
}
})
.otherwise({
redirectTo: "/login"
});
});
How It Works:
- When a user tries to access
/dashboard
,AuthService.isAuthenticated()
checks if they are logged in. - If not authenticated, the user is redirected to
/login
.
3. Creating an Authentication Service
Step 2: Create AuthService
for User Authentication
app.factory("AuthService", function($q) {
var user = null;
return {
login: function(username, password) {
var deferred = $q.defer();
if (username === "admin" && password === "password") {
user = { username: username };
deferred.resolve(user);
} else {
deferred.reject("Invalid credentials");
}
return deferred.promise;
},
logout: function() {
user = null;
},
isAuthenticated: function() {
var deferred = $q.defer();
deferred.resolve(user !== null);
return deferred.promise;
}
};
});
How It Works:
login(username, password)
: Verifies credentials and stores the user.logout()
: Clears user session.isAuthenticated()
: Returnstrue
orfalse
based on login status.
4. Handling Login and Logout
Step 3: Create a LoginController
app.controller("LoginController", function($scope, $location, AuthService) {
$scope.login = function() {
AuthService.login($scope.username, $scope.password)
.then(function() {
$location.path("/dashboard");
})
.catch(function(error) {
$scope.error = error;
});
};
});
How It Works:
- Calls
AuthService.login()
to authenticate the user. - If successful, redirects to
/dashboard
. - If login fails, displays an error message.
Step 4: Logout Functionality
app.controller("DashboardController", function($scope, $location, AuthService) {
$scope.logout = function() {
AuthService.logout();
$location.path("/login");
};
});
How It Works:
- Calls
AuthService.logout()
to clear user session. - Redirects the user to the login page.
5. Restricting Navigation with $rootScope
Instead of adding resolve
to every route, use $rootScope.$on("$routeChangeStart")
to globally check authentication.
app.run(function($rootScope, $location, AuthService) {
$rootScope.$on("$routeChangeStart", function(event, next) {
AuthService.isAuthenticated().then(function(isAuth) {
if (!isAuth && next.templateUrl !== "views/login.html") {
$location.path("/login");
}
});
});
});
How It Works:
- Before each route change, it checks authentication.
- If not logged in, redirects to
/login
.
6. Role-Based Route Protection
To restrict access based on user roles (e.g., Admin vs. User), modify AuthService
.
Step 1: Extend AuthService
to Store Roles
app.factory("AuthService", function($q) {
var user = null;
return {
login: function(username, password, role) {
var deferred = $q.defer();
if (username === "admin" && password === "password") {
user = { username: username, role: "admin" };
deferred.resolve(user);
} else if (username === "user" && password === "password") {
user = { username: username, role: "user" };
deferred.resolve(user);
} else {
deferred.reject("Invalid credentials");
}
return deferred.promise;
},
getUserRole: function() {
return user ? user.role : null;
},
isAuthenticated: function() {
var deferred = $q.defer();
deferred.resolve(user !== null);
return deferred.promise;
}
};
});
Step 2: Modify Routes to Restrict Access
app.config(function($routeProvider) {
$routeProvider
.when("/admin", {
templateUrl: "views/admin.html",
controller: "AdminController",
resolve: {
auth: function(AuthService, $location) {
return AuthService.isAuthenticated().then(function(isAuth) {
if (!isAuth || AuthService.getUserRole() !== "admin") {
$location.path("/login");
}
});
}
}
})
.when("/user", {
templateUrl: "views/user.html",
controller: "UserController",
resolve: {
auth: function(AuthService, $location) {
return AuthService.isAuthenticated().then(function(isAuth) {
if (!isAuth || AuthService.getUserRole() !== "user") {
$location.path("/login");
}
});
}
}
})
.otherwise({
redirectTo: "/login"
});
});
How It Works:
/admin
is only accessible to Admin users./user
is only accessible to Regular users.