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 authentication using JSON Web Tokens (JWT)

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

Loading

Why Use JWT for Authentication?

JSON Web Tokens (JWT) are a secure way to handle authentication because:
Stateless authentication (no need to store sessions on the server)
Easy to use with APIs (works well with RESTful services)
More secure than cookies (reduces CSRF attacks)


How JWT Authentication Works

  1. User logs in → Sends username & password to the server.
  2. Server verifies credentials → If valid, it generates a JWT.
  3. JWT is sent to the client → The client stores it (localStorage or sessionStorage).
  4. Client sends JWT in API requests → The token is included in the Authorization header.
  5. Server verifies JWT → If valid, it processes the request; otherwise, it rejects it.

1️⃣ Backend Setup (Node.js & Express)

We’ll create a simple Node.js API to generate and verify JWT tokens.

Install Required Packages

npm init -y
npm install express body-parser jsonwebtoken cors bcryptjs

Create server.js

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

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

const users = [{ username: "test", password: bcrypt.hashSync("password", 8) }];

const SECRET_KEY = "mysecretkey";

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

if (!user || !bcrypt.compareSync(password, user.password)) {
return res.status(401).json({ message: "Invalid credentials" });
}

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

// Protected Route
app.get("/protected", (req, res) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(403).json({ message: "No token provided" });

jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (err) return res.status(401).json({ message: "Invalid token" });
res.json({ message: "Access granted", user: decoded });
});
});

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

2️⃣ Frontend (AngularJS) Implementation

Step 1: Create an AngularJS App

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

Step 2: Create an Authentication Service

We’ll create a service to handle JWT login, storage, and API calls.

app.service("AuthService", function ($http, $window) {
var baseUrl = "http://localhost:3000";

// Login Function
this.login = function (credentials) {
return $http.post(baseUrl + "/login", credentials).then(function (response) {
$window.localStorage.setItem("token", response.data.token);
return response.data;
});
};

// 📌 Get JWT Token
this.getToken = function () {
return $window.localStorage.getItem("token");
};

// Check if User is Authenticated
this.isAuthenticated = function () {
return !!this.getToken();
};

// Logout Function
this.logout = function () {
$window.localStorage.removeItem("token");
};
});

Step 3: Use $http Interceptor to Attach JWT to API Requests

We need to attach the token to every API request using $httpProvider.interceptors.

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

app.config(function ($httpProvider) {
$httpProvider.interceptors.push("AuthInterceptor");
});

This ensures that every API call automatically includes the JWT!


Step 4: Create Login Controller

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

$scope.login = function () {
AuthService.login($scope.credentials)
.then(function () {
$window.location.href = "dashboard.html"; // Redirect after login
})
.catch(function () {
$scope.errorMessage = "Invalid username or password";
});
};
});

Step 5: Create Protected API Call

app.controller("DashboardController", function ($scope, $http, AuthService) {
$scope.userData = null;
$scope.errorMessage = "";

$http.get("http://localhost:3000/protected")
.then(function (response) {
$scope.userData = response.data;
})
.catch(function () {
$scope.errorMessage = "Unauthorized access!";
});

$scope.logout = function () {
AuthService.logout();
window.location.href = "index.html"; // Redirect after logout
};
});

Step 6: Create Login Page (index.html)

<!DOCTYPE html>
<html ng-app="jwtApp">
<head>
<title>Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="LoginController">
<h2>Login</h2>
<form ng-submit="login()">
<input type="text" ng-model="credentials.username" placeholder="Username" required />
<input type="password" ng-model="credentials.password" placeholder="Password" required />
<button type="submit">Login</button>
</form>
<p style="color: red;">{{ errorMessage }}</p>
</body>
</html>

Step 7: Create Dashboard Page (dashboard.html)

<!DOCTYPE html>
<html ng-app="jwtApp">
<head>
<title>Dashboard</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DashboardController">
<h2>Dashboard</h2>
<p>Welcome, {{ userData.user.username }}</p>
<button ng-click="logout()">Logout</button>
<p style="color: red;">{{ errorMessage }}</p>
</body>
</html>
Posted Under AngularJS$http Interceptor AngularJS AngularJS Authentication API security JSON Web Tokens JWT authentication Node.js Authentication Secure Login Token-Based Authentication

Post navigation

Streaming SSR Responses in React 18
Implementing Image Optimization in Next.js

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