AngularJS HTTP Auth Interceptor
angular-http-auth is an AngularJS module providing an HTTP interceptor to handle 401 (Unauthorized) and 403 (Forbidden) responses, facilitating robust authentication and authorization flows within AngularJS 1.x applications. It automatically buffers failed requests upon receiving a 401, broadcasts an `event:auth-loginRequired` event to trigger a login UI, and re-submits buffered requests once `authService.loginConfirmed()` is invoked. For 403 responses, it broadcasts `event:auth-forbidden`. The current stable version is 1.5.0, released in 2016. This package is now effectively abandoned due to its strict dependency on AngularJS 1.x, which reached End-of-Life on December 31, 2021. Its primary differentiator was its opinionated, event-driven approach to authentication challenges, deeply integrated into the AngularJS `$http` service.
Common errors
-
Error: [$injector:modulerr] Failed to instantiate module http-auth-interceptor due to: Error: [$injector:nomod] Module 'http-auth-interceptor' is not available!
cause The `http-auth-interceptor` module script was not loaded or `angular.module()` was called before the module was defined.fixEnsure the `angular-http-auth.js` (or `.min.js`) script is included in your HTML *after* `angular.js` and *before* your main application script. Verify the module name is correctly spelled in `angular.module('myApp', ['http-auth-interceptor'])`. -
ReferenceError: authService is not defined
cause The `authService` was attempted to be used without being properly injected into an Angular component (controller, service, etc.).fixEnsure `authService` is listed as a dependency in the function signature where it's being used, e.g., `app.controller('MyCtrl', function($scope, authService) { ... })`. -
HTTP 401 responses are not triggering login dialogs / are not being intercepted.
cause The module might not be correctly integrated into the AngularJS application, or a request has `ignoreAuthModule: true` set.fixVerify that `http-auth-interceptor` is included in your main Angular module's dependencies: `angular.module('myApp', ['http-auth-interceptor'])`. Also, check the `$http` config for the specific request to ensure `ignoreAuthModule: true` is not inadvertently present.
Warnings
- breaking This package is designed for AngularJS 1.x, which reached End-of-Life (EOL) on December 31, 2021. Using it in new projects or maintaining it in existing projects carries significant security and maintenance risks due to the EOL status of its core dependency.
- gotcha CommonJS loading (e.g., `require('angular-http-auth')`) was added in v1.5.0 but primarily ensures the Angular module is registered. Services like `authService` are still exposed via Angular's dependency injection and cannot be directly imported as ES Modules or CommonJS exports.
- gotcha To bypass the 401/403 interceptor for specific `$http` requests (e.g., a login API call that itself returns 401 for invalid credentials), you must add `ignoreAuthModule: true` to the request's config object.
- gotcha The `event:auth-forbidden` message (for HTTP 403 responses) was introduced in v1.2.2. Prior versions only handled HTTP 401 responses. Code relying on 403 handling will fail silently on older versions.
Install
-
npm install angular-http-auth -
yarn add angular-http-auth -
pnpm add angular-http-auth
Imports
- http-auth-interceptor
import { httpAuthInterceptor } from 'angular-http-auth'angular.module('myApp', ['http-auth-interceptor']) - authService
import { authService } from 'angular-http-auth'function MyController($scope, authService) { /* ... */ } - angular-http-auth
import 'angular-http-auth';
require('angular-http-auth');
Quickstart
const express = require('express');
const app = express();
const port = 3000;
app.get('/api/protected-data', (req, res) => {
const token = req.headers.authorization;
if (!token || token !== 'Bearer my-valid-token') {
return res.status(401).send('Unauthorized');
}
res.json({ message: 'This is protected data!' });
});
app.listen(port, () => console.log(`Backend listening on port ${port}`));
// --- In your AngularJS app (e.g., app.js) ---
// Make sure to include angular.js before angular-http-auth.js
// E.g., <script src="node_modules/angular/angular.js"></script>
// <script src="node_modules/angular-http-auth/dist/angular-http-auth.js"></script>
angular.module('myApp', ['http-auth-interceptor'])
.config(function($httpProvider) {
// $httpProvider.interceptors.push('authInterceptor'); // Not needed, http-auth-interceptor registers itself
})
.run(function($rootScope, $log, authService, $http) {
$rootScope.username = '';
$rootScope.password = '';
$rootScope.isAuthenticated = false;
$rootScope.$on('event:auth-loginRequired', function() {
$log.warn('Authentication required! Showing login dialog...');
// In a real app, you'd show a modal or redirect to a login page
$rootScope.showLoginDialog = true;
});
$rootScope.$on('event:auth-loginConfirmed', function(event, data) {
$log.info('Login confirmed!', data);
$rootScope.isAuthenticated = true;
$rootScope.showLoginDialog = false;
});
$rootScope.$on('event:auth-loginCancelled', function(event, data) {
$log.info('Login cancelled!', data);
$rootScope.isAuthenticated = false;
$rootScope.showLoginDialog = false;
});
$rootScope.login = function() {
// Simulate login request
$log.info(`Attempting login for ${$rootScope.username}`);
if ($rootScope.username === 'user' && $rootScope.password === 'pass') {
// Assuming a successful login would return a token or confirm success
// In a real app, this would be an actual $http call to your auth endpoint
$log.info('Simulated login successful. Confirming authService...');
authService.loginConfirmed({ token: 'my-valid-token', user: $rootScope.username });
} else {
$log.error('Invalid credentials.');
authService.loginCancelled(); // Clear buffered requests
}
};
$rootScope.logout = function() {
$log.info('Logging out...');
authService.loginCancelled();
$rootScope.username = '';
$rootScope.password = '';
};
// Example protected API call
$rootScope.fetchProtectedData = function() {
$http.get('/api/protected-data', {
headers: { 'Authorization': `Bearer ${$rootScope.isAuthenticated ? 'my-valid-token' : ''}` }
})
.then(function(response) {
$log.info('Protected data:', response.data);
})
.catch(function(error) {
if (error.status === 401) {
$log.error('Failed to fetch protected data: Unauthorized. Interceptor should handle this.');
} else {
$log.error('Error fetching protected data:', error);
}
});
};
// Call it initially to demonstrate behavior
$rootScope.fetchProtectedData();
});