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:
- User logs in → API verifies credentials and returns a JWT token.
- Frontend stores token in localStorage or sessionStorage.
- Every API request includes JWT in the Authorization header.
- 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.