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

Protecting routes using Authentication

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

Loading

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(): Returns true or false 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.
Posted Under AngularJS$location.path $rootScope.$on $routeChangeStart $routeProvider AngularJS AngularJS Security Authentication Login Logout Middleware Authentication ngRoute Role-Based Access route protection Secure Routes session management user roles

Post navigation

Container-Presenter Pattern
Controlled vs. Uncontrolled Components

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