Authorizing HTTP Requests
Learn how to add authentication tokens in HTTP request headers.
We'll cover the following...
The Fake Store API does not require authorization while communicating with its endpoints. However, consider that we are working with a backend API that expects all HTTP requests to contain an authentication token using HTTP headers. A common pattern in web applications is to include the token in an Authorization header.
Streamlining HTTP requests with custom headers
We can use HTTP headers in an Angular application by importing the HttpHeaders
artifact from the @angular/common/http
namespace and modifying our methods accordingly:
getProducts(): Observable<Product[]> {const options = {headers: new HttpHeaders({ Authorization: 'myAuthToken' })};return this.http.get<ProductDTO[]>(this.productsUrl, options).pipe(map(products => products.map(product => {return this.convertToProduct(product);})));}
For simplicity, we are using a hardcoded value for the authentication token. In a real-world scenario, we may get it from the local storage of the browser or some other means.
All HttpClient
methods accept an optional object as a parameter for passing additional options to an HTTP request. Request options can be an HTTP ...