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 JWT authentication using $http service

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

Loading

JSON Web Token (JWT) authentication is a secure way to manage user sessions in AngularJS applications. It allows users to authenticate with a token-based system, eliminating the need for traditional session cookies.

What We’ll Cover:

What is JWT authentication?
Steps to implement JWT authentication in AngularJS
Creating a login system with JWT
Attaching JWT to API requests
Protecting routes using authentication checks


1️⃣ What is JWT Authentication?

JWT authentication works by:

  1. User logs in → API verifies credentials and returns a JWT token.
  2. Frontend stores token in localStorage or sessionStorage.
  3. Every API request includes JWT in the Authorization header.
  4. Backend validates JWT before processing requests.

2️⃣ Steps to Implement JWT Authentication in AngularJS

Step 1: Set Up AngularJS App

Create an AngularJS module and configure routing.

var app = angular.module("myApp", ["ngRoute"]);

app.config(function ($routeProvider) {
$routeProvider
.when("/login", {
templateUrl: "login.html",
controller: "LoginController"
})
.when("/dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardController",
resolve: {
auth: function (AuthService, $location) {
if (!AuthService.isAuthenticated()) {
$location.path("/login");
}
}
}
})
.otherwise({
redirectTo: "/login"
});
});

🔹 resolve ensures protected routes: Redirects users if they’re not logged in.


Step 2: Create an Authentication Service

The AuthService handles login, logout, and token management.

app.factory("AuthService", function ($http, $window) {
var authService = {};

// Login function
authService.login = function (credentials) {
return $http.post("/api/login", credentials).then(function (response) {
if (response.data.token) {
$window.localStorage.setItem("jwtToken", response.data.token);
return response.data;
}
});
};

// Check if user is authenticated
authService.isAuthenticated = function () {
return !!$window.localStorage.getItem("jwtToken");
};

// Logout function
authService.logout = function () {
$window.localStorage.removeItem("jwtToken");
};

return authService;
});

🔹 How It Works:

  • Login → Calls backend API and stores JWT.
  • isAuthenticated() → Checks if JWT exists.
  • Logout → Clears JWT from localStorage.

Step 3: Implement Login Controller

Create a controller to handle user login.

app.controller("LoginController", function ($scope, AuthService, $location) {
$scope.credentials = { username: "", password: "" };

$scope.login = function () {
AuthService.login($scope.credentials)
.then(function () {
$location.path("/dashboard"); // Redirect on success
})
.catch(function () {
alert("Invalid credentials");
});
};
});

🔹 Validates credentials and redirects to the dashboard on success.


Step 4: Attach JWT to Every API Request

To secure API calls, add the JWT to every HTTP request using an $http interceptor.

app.factory("AuthInterceptor", function ($window) {
return {
request: function (config) {
var token = $window.localStorage.getItem("jwtToken");
if (token) {
config.headers.Authorization = "Bearer " + token;
}
return config;
}
};
});

// Register the interceptor
app.config(function ($httpProvider) {
$httpProvider.interceptors.push("AuthInterceptor");
});

🔹 Why Use This?

  • Automatically attaches the JWT to every outgoing API request.
  • Ensures only authenticated users can access protected endpoints.

Step 5: Protecting Routes Using Authentication

Modify DashboardController to restrict access to logged-in users.

app.controller("DashboardController", function ($scope, AuthService, $location) {
if (!AuthService.isAuthenticated()) {
$location.path("/login"); // Redirect unauthorized users
}

$scope.logout = function () {
AuthService.logout();
$location.path("/login");
};
});

🔹 Ensures users can’t access the dashboard without a valid token.


Step 6: Backend API (Node.js + Express Example)

The backend should return a JWT token after a successful login.

const express = require("express");
const jwt = require("jsonwebtoken");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());

const SECRET_KEY = "my_secret_key";

const users = [{ username: "admin", password: "password123" }];

// Login endpoint
app.post("/api/login", (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);

if (!user) {
return res.status(401).json({ message: "Invalid credentials" });
}

const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: "1h" });
res.json({ token });
});

// Protected endpoint
app.get("/api/dashboard", verifyToken, (req, res) => {
res.json({ message: "Welcome to the Dashboard!" });
});

// Middleware to verify token
function verifyToken(req, res, next) {
const token = req.headers["authorization"];
if (!token) {
return res.status(403).json({ message: "Access Denied" });
}

jwt.verify(token.split(" ")[1], SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(401).json({ message: "Invalid Token" });
}
req.user = decoded;
next();
});
}

app.listen(5000, () => console.log("Server running on port 5000"));

🔹 Backend Responsibilities:

  • Validates login credentials.
  • Generates a JWT token (expires in 1 hour).
  • Uses middleware to protect routes.

7️⃣ Testing the Authentication Flow

1️⃣ Start the Backend Server:

bashCopyEditnode server.js

2️⃣ Run the AngularJS App:
Serve your AngularJS files and access http://localhost:4200.

3️⃣ Login:

  • Enter username/password (admin/password123).
  • A JWT token is stored in localStorage.

4️⃣ Access Protected Routes:

  • Open Dashboard → Should work if authenticated.
  • Remove the JWT from localStorage and reload → Redirected to login.
Posted Under AngularJS$http Service AngularJS AngularJS Login Authentication Express API JWT authentication Node.js Secure API Requests Token-Based Authentication Web Security

Post navigation

Using $http interceptors for modifying API requests
Using $resource for RESTful services

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