In AngularJS, route authentication ensures that only authenticated users can access certain routes. This can be done using the $routeChangeStart
event, which triggers before a route change occurs.
1. Understanding $routeChangeStart
$routeChangeStart
is an event fired before the route actually changes. You can use it to check if a user is logged in and either allow or prevent navigation.
Flow of Route Authentication
- User tries to access a route.
$routeChangeStart
triggers.- The app checks if the user is authenticated.
- If authenticated, the user is allowed to access the route.
- If not authenticated, the user is redirected to the login page.
2. Steps to Implement Route Authentication
Step 1: Include AngularJS and ngRoute
Ensure you include AngularJS and angular-route.js
in your index.html
.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>
Step 2: Define the AngularJS App and Routing
Create the AngularJS module and configure routes using $routeProvider
.
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "HomeController"
})
.when("/dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardController",
protected: true // Custom property to mark protected routes
})
.when("/login", {
templateUrl: "login.html",
controller: "LoginController"
})
.otherwise({
redirectTo: "/"
});
});
Notice the protected: true
property in the /dashboard
route. This helps us identify routes that need authentication.
Step 3: Create a Simple Authentication Service
This service manages user login, logout, and authentication status.
app.factory("AuthService", function() {
var user = null; // Stores user authentication state
return {
login: function(username, password) {
if (username === "admin" && password === "1234") { // Example credentials
user = { username: username };
return true;
}
return false;
},
logout: function() {
user = null;
},
isAuthenticated: function() {
return user !== null;
}
};
});
Step 4: Implement Route Protection Using $routeChangeStart
Listen for route changes and prevent unauthorized users from accessing protected routes.
app.run(function($rootScope, $location, AuthService) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
// Check if the route requires authentication
if (next.protected && !AuthService.isAuthenticated()) {
event.preventDefault(); // Stop the navigation
$location.path("/login"); // Redirect to login page
}
});
});
✔ How It Works
- Before any route change,
$routeChangeStart
checks if the route hasprotected: true
. - If the user is not authenticated, it stops navigation (
event.preventDefault()
) and redirects to login page.
Step 5: Create Login Controller
Handle user login and store authentication status.
app.controller("LoginController", function($scope, $location, AuthService) {
$scope.login = function() {
var success = AuthService.login($scope.username, $scope.password);
if (success) {
$location.path("/dashboard"); // Redirect to dashboard after login
} else {
$scope.error = "Invalid credentials!";
}
};
});
Step 6: Create the Views (HTML Files)
1. index.html
(Main File)
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>AngularJS Route Authentication</title>
</head>
<body>
<nav>
<a href="#!/">Home</a> |
<a href="#!/dashboard">Dashboard</a> |
<a href="#!/login">Login</a>
</nav>
<div ng-view></div>
</body>
</html>
2. home.html
(Public Page)
<h2>Home Page</h2>
<p>Welcome to our AngularJS app.</p>
3. dashboard.html
(Protected Page)
<h2>Dashboard</h2>
<p>This is a protected page. Only logged-in users can see this.</p>
4. login.html
(Login Page)
<h2>Login</h2>
<form ng-submit="login()">
<input type="text" ng-model="username" placeholder="Username" required>
<input type="password" ng-model="password" placeholder="Password" required>
<button type="submit">Login</button>
<p style="color: red;">{{ error }}</p>
</form>
7. Testing the Authentication
- Try accessing
http://localhost/#!/dashboard
without logging in.- You should be redirected to
/login
.
- You should be redirected to
- Enter valid credentials (
admin / 1234
) and click Login.- You should be redirected to Dashboard.
- Refresh the page while on Dashboard.
- If you reload, you might be logged out (modify
AuthService
to store session data if needed).
- If you reload, you might be logged out (modify
8. Enhancements and Security
Persist User Login (Using LocalStorage)
Modify AuthService
to store login state in localStorage
.
app.factory("AuthService", function() {
return {
login: function(username, password) {
if (username === "admin" && password === "1234") {
localStorage.setItem("user", JSON.stringify({ username }));
return true;
}
return false;
},
logout: function() {
localStorage.removeItem("user");
},
isAuthenticated: function() {
return localStorage.getItem("user") !== null;
}
};
});