Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Implementing route authentication using $routeChangeStart

Posted on March 27, 2025March 27, 2025 by Rishan Solutions

Loading

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

  1. User tries to access a route.
  2. $routeChangeStart triggers.
  3. The app checks if the user is authenticated.
  4. If authenticated, the user is allowed to access the route.
  5. 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 has protected: 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

  1. Try accessing http://localhost/#!/dashboardwithout logging in.
    • You should be redirected to /login.
  2. Enter valid credentials (admin / 1234) and click Login.
    • You should be redirected to Dashboard.
  3. Refresh the page while on Dashboard.
    • If you reload, you might be logged out (modify AuthService to store session data if needed).

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;
}
};
});
Posted Under AngularJS$routeChangeStart AngularJS $routeProvider AngularJS Authentication AngularJS Routing Login System Protected Routes Route Guard Secure Routes Single Page Application user authentication

Post navigation

How $routeProvider works in AngularJS?
Lazy loading modules using AngularJS routing

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions