Published: March 29 2023

Angular - Add Bearer Token Authorization Header to HTTP Request

Below is a quick example of how to add a Bearer Token Authorization Header to an HTTP request in Angular using the HttpClient which is part of the Angular HttpClientModule.


Angular Bearer Token

This sends an HTTP GET request to the Test JSON API with the HTTP Authorization header set to a bearer token. The Test JSON API is a fake online REST API that includes a product details route (/products/{id}), the returned product includes an id and name.

After the JSON data is fetched from the API it is assigned to the product component property and rendered in the Angular template.

Add Authorization Header

The auth header with bearer token is added to the request by passing a custom headers object (e.g. { headers: { 'Authorization': 'Bearer my-token' } }) as the second parameter to the http.get() method. The second param contains the request options and it supports a bunch of different options for making HTTP requests including setting headers, a complete list is available at https://angular.io/guide/http.

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

@Component({ selector: 'app-root', templateUrl: 'app.component.html' })
export class AppComponent { 
    product: any;

    constructor(private http: HttpClient) { }

    ngOnInit() {
        const headers = { 'Authorization': 'Bearer my-token' }
        this.http.get<any>('https://testapi.jasonwatmore.com/products/1', { headers })
            .subscribe(data => this.product = data);
    }
}

See the Angular request with bearer token on StackBlitz at https://stackblitz.com/edit/angular-bearer-token


More Angular Request Examples

For more Angular HTTP examples see Angular - HTTP GET Request Examples.

 


Need Some Angular Help?

Search fiverr for freelance Angular developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by