{"id":16289,"library":"angular-http-auth","title":"AngularJS HTTP Auth Interceptor","description":"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.","status":"abandoned","version":"1.5.0","language":"javascript","source_language":"en","source_url":"https://github.com/witoldsz/angular-http-auth","tags":["javascript","angular","auth"],"install":[{"cmd":"npm install angular-http-auth","lang":"bash","label":"npm"},{"cmd":"yarn add angular-http-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add angular-http-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This module is a direct extension of AngularJS 1.x's `$http` service and requires Angular to function.","package":"angular","optional":false}],"imports":[{"note":"This is the name of the AngularJS module to be included in your application's dependencies, not a direct JavaScript import.","wrong":"import { httpAuthInterceptor } from 'angular-http-auth'","symbol":"http-auth-interceptor","correct":"angular.module('myApp', ['http-auth-interceptor'])"},{"note":"The `authService` is provided via AngularJS's dependency injection system, not as a direct ES Module or CommonJS export for consumer-side import. It should be injected into controllers, services, or directives.","wrong":"import { authService } from 'angular-http-auth'","symbol":"authService","correct":"function MyController($scope, authService) { /* ... */ }"},{"note":"For CommonJS environments (supported since v1.5.0), the package can be loaded via `require`. This makes the Angular module available but doesn't export any symbols directly to the requiring file. Direct ESM imports are not supported.","wrong":"import 'angular-http-auth';","symbol":"angular-http-auth","correct":"require('angular-http-auth');"}],"quickstart":{"code":"const express = require('express');\nconst app = express();\nconst port = 3000;\n\napp.get('/api/protected-data', (req, res) => {\n  const token = req.headers.authorization;\n  if (!token || token !== 'Bearer my-valid-token') {\n    return res.status(401).send('Unauthorized');\n  }\n  res.json({ message: 'This is protected data!' });\n});\n\napp.listen(port, () => console.log(`Backend listening on port ${port}`));\n\n\n// --- In your AngularJS app (e.g., app.js) ---\n\n// Make sure to include angular.js before angular-http-auth.js\n// E.g., <script src=\"node_modules/angular/angular.js\"></script>\n//       <script src=\"node_modules/angular-http-auth/dist/angular-http-auth.js\"></script>\n\nangular.module('myApp', ['http-auth-interceptor'])\n  .config(function($httpProvider) {\n    // $httpProvider.interceptors.push('authInterceptor'); // Not needed, http-auth-interceptor registers itself\n  })\n  .run(function($rootScope, $log, authService, $http) {\n    $rootScope.username = '';\n    $rootScope.password = '';\n    $rootScope.isAuthenticated = false;\n\n    $rootScope.$on('event:auth-loginRequired', function() {\n      $log.warn('Authentication required! Showing login dialog...');\n      // In a real app, you'd show a modal or redirect to a login page\n      $rootScope.showLoginDialog = true;\n    });\n\n    $rootScope.$on('event:auth-loginConfirmed', function(event, data) {\n      $log.info('Login confirmed!', data);\n      $rootScope.isAuthenticated = true;\n      $rootScope.showLoginDialog = false;\n    });\n\n    $rootScope.$on('event:auth-loginCancelled', function(event, data) {\n      $log.info('Login cancelled!', data);\n      $rootScope.isAuthenticated = false;\n      $rootScope.showLoginDialog = false;\n    });\n\n    $rootScope.login = function() {\n      // Simulate login request\n      $log.info(`Attempting login for ${$rootScope.username}`);\n      if ($rootScope.username === 'user' && $rootScope.password === 'pass') {\n        // Assuming a successful login would return a token or confirm success\n        // In a real app, this would be an actual $http call to your auth endpoint\n        $log.info('Simulated login successful. Confirming authService...');\n        authService.loginConfirmed({ token: 'my-valid-token', user: $rootScope.username });\n      } else {\n        $log.error('Invalid credentials.');\n        authService.loginCancelled(); // Clear buffered requests\n      }\n    };\n\n    $rootScope.logout = function() {\n      $log.info('Logging out...');\n      authService.loginCancelled();\n      $rootScope.username = '';\n      $rootScope.password = '';\n    };\n\n    // Example protected API call\n    $rootScope.fetchProtectedData = function() {\n      $http.get('/api/protected-data', {\n        headers: { 'Authorization': `Bearer ${$rootScope.isAuthenticated ? 'my-valid-token' : ''}` }\n      })\n      .then(function(response) {\n        $log.info('Protected data:', response.data);\n      })\n      .catch(function(error) {\n        if (error.status === 401) {\n          $log.error('Failed to fetch protected data: Unauthorized. Interceptor should handle this.');\n        } else {\n          $log.error('Error fetching protected data:', error);\n        }\n      });\n    };\n\n    // Call it initially to demonstrate behavior\n    $rootScope.fetchProtectedData();\n  });","lang":"javascript","description":"This quickstart demonstrates setting up a basic Express backend that requires authentication and an AngularJS application that utilizes `angular-http-auth` to intercept 401 responses, trigger a simulated login process, and re-attempt the failed request."},"warnings":[{"fix":"Migrate to a modern framework (e.g., Angular 2+, React, Vue) and use a contemporary authentication solution. If migration is not feasible, understand and mitigate the risks associated with using EOL software.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Ensure you are using v1.5.0 or later for CommonJS support. Always inject `authService` using Angular's DI, e.g., `function($scope, authService) { ... }`, rather than attempting direct import.","message":"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.","severity":"gotcha","affected_versions":"<1.5.0"},{"fix":"When making an HTTP request that should not trigger the authentication interceptor, add `{ ignoreAuthModule: true }` as the config object, e.g., `$http.post('/login', credentials, { ignoreAuthModule: true })`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `angular-http-auth` is at least version 1.2.2 if your application needs to specifically handle 403 responses. Upgrade to the latest available version (1.5.0) for full functionality.","message":"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.","severity":"gotcha","affected_versions":"<1.2.2"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure 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'])`.","cause":"The `http-auth-interceptor` module script was not loaded or `angular.module()` was called before the module was defined.","error":"Error: [$injector:modulerr] Failed to instantiate module http-auth-interceptor due to: Error: [$injector:nomod] Module 'http-auth-interceptor' is not available!"},{"fix":"Ensure `authService` is listed as a dependency in the function signature where it's being used, e.g., `app.controller('MyCtrl', function($scope, authService) { ... })`.","cause":"The `authService` was attempted to be used without being properly injected into an Angular component (controller, service, etc.).","error":"ReferenceError: authService is not defined"},{"fix":"Verify 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.","cause":"The module might not be correctly integrated into the AngularJS application, or a request has `ignoreAuthModule: true` set.","error":"HTTP 401 responses are not triggering login dialogs / are not being intercepted."}],"ecosystem":"npm"}