Implementing Automatic Authorization Headers for Every HTTP Request in Angular

Nov 09, 2025 · Programming · 15 views · 7.8

Keywords: Angular | HTTP Headers | Authentication | Interceptors | HttpClient

Abstract: This article provides an in-depth exploration of three primary methods for automatically adding authorization headers to all HTTP requests in Angular applications: custom HttpClient wrapper, HTTP interceptors, and extending BaseRequestOptions. Through detailed code examples and comparative analysis, it demonstrates the advantages, limitations, and best practices of each approach, helping developers build more secure and maintainable authentication mechanisms.

Introduction

In modern web application development, user authentication is a core requirement. Once a user successfully logs in, it's typically necessary to automatically include authentication tokens or other credentials in all subsequent HTTP requests. Manually adding headers to each request is not only tedious but also error-prone. The Angular framework offers several elegant solutions to address this need.

Custom HttpClient Wrapper Approach

In earlier versions of Angular, a common practice was to create a custom HttpClient service that wraps the native Http service. This approach encapsulates HTTP methods to automatically add authorization headers with each call.

First, we need to create a custom HttpClient service:

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class HttpClient {
  constructor(private http: Http) {}

  createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' + btoa('username:password'));
  }

  get(url) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, { headers: headers });
  }

  post(url, data) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, { headers: headers });
  }
}

In this implementation, we create a HttpClient class that wraps the native Http service. The createAuthorizationHeader method is responsible for adding authentication information to headers, while the get and post methods automatically create headers and add authentication information with each request call.

When using it in components, we inject the custom HttpClient instead of the native Http service:

import { HttpClient } from './http-client';

export class MyComponent {
  constructor(private http: HttpClient) {}

  handleSomething() {
    this.http.post(url, data).subscribe(result => {
      // Process response result
    });
  }
}

The advantage of this approach is its simplicity and clear, understandable code. However, it requires manually wrapping all needed HTTP methods and may require adjustments during Angular version upgrades.

HTTP Interceptor Approach

Starting from Angular 4.3, a more powerful HTTP interceptor mechanism was introduced. Interceptors allow us to insert custom logic before requests are sent and after responses are received, making them an ideal solution for global header management.

The basic steps to create an HTTP interceptor are:

import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({ 
      setHeaders: { Authorization: 'Bearer 123' }
    });
    return next.handle(clonedRequest);
  }
}

It's important to note the principle of HTTP request immutability. We cannot directly modify the original HttpRequest object; instead, we must create a copy using the clone method and then make modifications on the copy.

Registering the interceptor requires providing it in the application module:

import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AddHeaderInterceptor,
    multi: true,
  }],
})
export class AppModule {}

The advantage of the interceptor approach is its global nature and non-invasiveness. Once configured, all requests made through HttpClient automatically pass through the interceptor processing without modifying existing business code.

Extending BaseRequestOptions Approach

In early versions of Angular 2, global header management could also be achieved by extending BaseRequestOptions:

import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http';

class MyRequestOptions extends BaseRequestOptions {
  constructor() {
    super();
    this.headers.append('My-Custom-Header', 'MyCustomHeaderValue');
  }
}

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(RequestOptions, { useClass: MyRequestOptions })
]);

This approach adds uniform headers to all requests by replacing the default RequestOptions implementation during application bootstrap. While simple to implement, it lacks flexibility and makes dynamic header management difficult.

Security Considerations and Best Practices

When automatically adding authentication headers to all requests, security risks must be carefully considered. Globally adding authentication headers means that all outbound requests, including those to third-party services, will carry authentication information. This could create serious security vulnerabilities.

Recommended best practices include:

Method Comparison and Selection Recommendations

Each of the three methods has its advantages and disadvantages:

For new projects, the HTTP interceptor approach is strongly recommended. It not only provides the most elegant implementation but also integrates well with other interceptor functionalities such as request retry and error handling.

Conclusion

Automatic management of HTTP request headers is a crucial aspect of building modern web applications. By appropriately selecting and applying the methods discussed, developers can build authentication systems that are both secure and maintainable. As the Angular framework continues to evolve, HTTP interceptors have become the standard approach for implementing this requirement, and developers are encouraged to prioritize their use in practical projects.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.