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
- User logs in → Sends username & password to the server.
- Server verifies credentials → If valid, it generates a JWT.
- JWT is sent to the client → The client stores it (localStorage or sessionStorage).
- Client sends JWT in API requests → The token is included in the
Authorization
header. - 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>