Using $httpInterceptor to attach tokens to API requests

Loading

Why Use $httpInterceptor?

$httpInterceptor in AngularJS is a powerful feature that allows us to modify API requests and responses before they reach the server or the application. It is commonly used for:

Attaching JWT Tokens → Ensures every request is authenticated
Handling API Errors → Automatically log out users on token expiration
Logging Requests and Responses → Debugging API interactions


How $httpInterceptor Works

  1. Intercept requests before they are sent to the server.
  2. Modify request headers (e.g., add authentication tokens).
  3. Intercept responses and handle errors globally.
  4. Reject or modify requests/responses before they reach the application.

1️⃣ Basic Setup of $httpInterceptor

To attach a JWT token to API requests, we need to:
🔹 Create a factory service for the interceptor
🔹 Inject it into $httpProvider

Step 1: Define the Interceptor Factory

Create an interceptor to attach the Authorization header to all outgoing HTTP requests.

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

responseError: function (response) {
if (response.status === 401 || response.status === 403) {
console.error("Unauthorized! Redirecting to login.");
$window.location.href = "index.html"; // Redirect to login on failure
}
return Promise.reject(response);
}
};
});

Step 2: Inject Interceptor into $httpProvider

To activate the interceptor, we must add it to the AngularJS configuration.

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

2️⃣ Testing the $httpInterceptor

Now, let’s make an API request using $http to see the interceptor in action.

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

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

The Authorization header will be automatically added to this request.
If the token is missing or expired, the responseError function will handle it.


3️⃣ Extending $httpInterceptor for Better Handling

We can improve our interceptor to:
Handle token refresh
Show error messages dynamically
Log API request times for debugging

Enhanced $httpInterceptor

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

response: function (response) {
console.log("API Call Successful:", response.config.url);
return response;
},

responseError: function (response) {
console.error("API Error:", response.config.url, response.status);
if (response.status === 401) {
alert("Session expired! Please log in again.");
$window.location.href = "index.html"; // Redirect to login page
}
return $q.reject(response);
}
};
});

4️⃣ Storing JWT Securely

For security reasons, use sessionStorage instead of localStorage to store JWT tokens.

sessionStorage.setItem("token", response.data.token); // Secure JWT storage

Why?
Prevents XSS attacks (tokens are cleared when the session ends).
Still allows authentication without persistent storage.

Leave a Reply

Your email address will not be published. Required fields are marked *