how to pass basic auth for api in angular 11

How to Pass Basic Auth for API in Angular 11?

Passing Basic Auth for API in Angular 11 is a common requirement for many web applications. Basic Auth is a simple authentication method that requires a username and password to be sent with every request to the server. In Angular 11, we can pass Basic Auth in two ways:

Method 1: Using HttpHeaders

The first method is to use the HttpHeaders class in Angular's HttpClient module. This method involves creating an instance of HttpHeaders and setting the Authorization header to the Basic Auth credentials. Here's an example:

    const headers = new HttpHeaders({
      Authorization: 'Basic ' + btoa(username + ':' + password)
    this.http.get(url, { headers }).subscribe(result => {

In this example, we're creating a new HttpHeaders object and setting the Authorization header to the Basic Auth credentials using the btoa() function. We're then passing the headers object in the options parameter of the HttpClient's get() method.

Method 2: Using Interceptors

The second method is to use interceptors in Angular. Interceptors are middleware functions that can intercept HTTP requests or responses. We can use an interceptor to add the Basic Auth credentials to every request made by the HttpClient. Here's an example:

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

    export class BasicAuthInterceptor implements HttpInterceptor {

      intercept(request: HttpRequest, next: HttpHandler) {
        const username = 'myusername';
        const password = 'mypassword';
        request = request.clone({
          setHeaders: {
            Authorization: 'Basic ' + btoa(username + ':' + password)
        return next.handle(request);

In this example, we're creating a new interceptor class called BasicAuthInterceptor. This class implements the HttpInterceptor interface, which requires us to implement the intercept() method. In the intercept() method, we're retrieving the Basic Auth credentials and setting the Authorization header on the request object using the clone() method. We're then returning the handle() method of the HttpHandler object to pass the request through to the next interceptor or to the HttpClient.

These are the two different ways to pass Basic Auth for API in Angular 11. Choose whichever method best suits your needs and integrate it into your application.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]