How to send authorization header in Angular 14

How to send authorization header in Angular 14

In this tutorial we'll learn how to send authorization header or pass the bearer token in Angular 14 by setting the authorization header using Angular 14 HttpClient. The bearer token is also called JWT token.

We can use the authorization header to pass different things such as: - The username and password - The api key, etc.

We will demonstrate how to use a bearer token in an angular header using easy to follow example of passing a token in the Angular header. The auth strategy is called token-based authentication which is used in many SPA frameworks such as in Angular 14 when used with a REST API backend.

We'll start by making a simple Angular 14 example then we'll see how to set the authorisation header.

To demonstrate how to include an authorization bearer token in an HTTP request's header, We'll use the following scenario. For each of Angular's HTTP methods—get, post, put, and delete—we will make use of HttpHeaders to transmit additional data.

This is an example of how to send the token from an Angular 14 component:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Angular 14 auth header example';
  constructor(public http: HttpClient) {}

  ngOnInit() {
    let api_key = "API_KEY_HERE";
    const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${api_key}`
      });

    const requestOptions = { headers: headers };

    this.http.get('<YOUR_API_URL>', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });
  }
}

Now, let's see the full example step by step.

How to add an Authorization Header to HTTP requests in Angular

I'm going to assume you already have an Angular 14 project up and running and have the Api key.

First, you'll want to make a HttpInterceptor. For this purpose, a service must first be created.

Head over to your terminal, if your project has been created with Angular CLI, and run the following command:

ng generate service api-interceptor

Open the src/app/api-interceptor.service.ts file and update it as follows:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer YOUR_KEY_HERE`
      }
    });

    return next.handle(request);
  }
}

Don't firget to replace YOUR_KEY_HERE with your real API key.

The following header will now be included to every HTTP request your app makes:

"Authorization": "Bearer YOUR_KEY_HERE"

In all likelihood, the data used by your Angular-based single-page app comes via a secured API endpoint. The addition of an Api-Key to the header of each request to this endpoint is one of the simplest and least cumbersome kinds of security.