AngularJS HTTP Auth Interceptor

1.5.0 · abandoned · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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.

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();
  });

view raw JSON →