What is the process for incorporating a bearer token generated for other API requests into the authorisation header?

I have developed a feature that communicates with an external API endpoint. I have utilized their authentication endpoint to generate a bearer token which I will utilize in subsequent API requests.

Considering this is a third-party API, the URLs and headers for my destination are constructed via a proxy.

Now that I have obtained the access_token, how can I include this token in the authorization header?

https://i.sstatic.net/Dmrzg.png

Component

 showOAuth() {
    this.zebraService.getOAuth()
      .subscribe((data: any) => {
      console.log('Zebra Response: ', data);
      console.log(data.body);
      this.OAuth = data.body;

      this.access_token = this.OAuth.access_token;
      console.log(this.access_token);
      });
  }

Proxy

"/zebraAccessApi": {
  "target": "https://api.com",
  "secure": true,
  "changeOrigin": true,
  "pathRewrite": {
    "^/zebraAccessApi": ""
  },
  "headers": {
    "client_id": "",
    "client_secret": ""
  }
},

"/zebraSetAppLed": {
  "target": "https://api.com/setAppLed",
  "secure": true,
  "changeOrigin": true,
  "pathRewrite": {
    "^/zebraSetAppLed": ""
  },
  "headers": {
    "Content-Type": "application/json",
    "Authorization": ""
  }
}

Service

zebraOAuthUrl = '/zebraAccessApi';
    zebraSetAppLedUrl = '/zebraSetAppLed';

    public getOAuth() {    
        let options = {
            observe: 'response' as 'body',
            response: 'json'
        };
        return this.http.get(this.zebraOAuthUrl, options);
    }

Answer №1

If you're looking to customize your HTTP requests with specific headers, consider creating an interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const authenticationToken = <YOUR_TOKEN>;

  // Add default headers if no token is provided
   const requestWithoutToken = request.clone({
    setHeaders: {
      'Content-Type': 'application/json', 
    }
  });
  if (!authenticationToken) {
    return next.handle(requestWithoutToken);
  }

  // Customize the headers here based on the presence of a token
  const updatedRequest = request.clone({
    setHeaders: {
      Authorization: `Bearer ${authenticationToken}`,
      'Content-Type': 'application/json',
    }
  });

  // Handle response and errors
  return next.handle(updatedRequest).pipe(
    tap((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // Do something with the response data
      }
    }, (error: any) => {
      if (error instanceof HttpErrorResponse) {
        console.log(error)
      }
    })
  );
}

An interceptor plays a crucial role in manipulating HTTP requests by adding necessary headers like authentication tokens. You can tailor this function according to your requirements.

To learn more about Angular interceptors, visit: https://angular.io/api/common/http/HttpInterceptor

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error during Angular AOT compilation: The 'length' property is not available on the 'AbstractControl' type

I'm facing an issue with my app where I am trying to implement AOT for faster loading times. However, I am running into a compilation error when using ngc and AOT settings, specifically related to validating the FormA. In my TypeScript code, I have a ...

Stop focusing on mat-select after a selection is made

I am encountering an issue with the following code in my .html file: <mat-form-field> <mat-select #selector(selectionChange)="onSelectionChange($event.value)"> <mat-option *ngFor="let test of tests" [value]="test"> </ma ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

Creating a search functionality in Angular that allows users to input multiple search terms and

I am currently delving into the world of Angular in combination with an API, and I have managed to set up a search box for querying data. However, I am facing a challenge where I cannot perform multiple searches successfully. Even though I can initially se ...

A guide to setting initial values in Angular 2 using TypeScript

My Rank class includes attributes for "loses" and "wins" obtained from a web service. I need to calculate the "points" attribute based on these values. For example: for(int i = 0; i<loses; i++{ points += 1; } for(int i = 0; i<wins; i++{ point ...

Finding the index of a chosen option in Angular

Attempting to retrieve the index of the selected option from a select element using Angular. The Angular (4) and Ionic 3 frameworks are being utilized. The template structure is as follows: <ion-select [(ngModel)]="obj.city"> <ion-option ...

Setting the first day of the week in ngbBootstrap DatePicker Configuration

I'm having trouble setting Sunday as the first day of the week in the ngbBootstrap datepicker. The documentation suggests it should be easy. I am using NgbBootstrap v1.1.2 and following the code documentation: Configuration service for the NgbDatep ...

Removing a request that lacks the id parameter in a .NET WebAPI

My .net core WebApi is functioning flawlessly, except when I use [HttpDelete] instead of [HttpDelete("{id}")]. Why might this be happening? Here is my URL: http://localhost:5004/api/Student/DeleteStudent/23 [ApiController] [Route("api/[controller]/[actio ...

Struggling to import a React component for sharing purposes

I've developed a React component that I want to share through a locally hosted npm repository. To achieve this, I created the React component using typescript, transpiled it to JavaScript, and then published the resulting code to the repository. Howe ...

Having difficulty building a react.js application using Visual Studio 2019

Currently, I am following a helpful tutorial on creating a react.js application using visual studio. At this stage, the tutorial instructs me to open the command prompt and enter the following command: webpack app.tsx --config webpack-config.js (I have ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Ensuring successful payment by facilitating the transfer of user id values to Stripe

In my current setup, I have an Angular application paired with an Express backend written in TypeScript. Each user is assigned a unique user ID and once payment is successfully processed, I need to update the database to reflect their new status as a pay ...

The Angular reactive form is being submitted without completing the submission process

I've been working on an Angular 5 reactive form and everything seems to be functioning correctly. However, I've encountered a strange issue with a button used to close the form by hiding it from view. Whenever I click on this close button, the f ...

"Navigating back to the previous screen in Ionic 2 - A step-by-step guide

When using Ionic q, we can go back to the previous screen with $ionichistory.goback(). However, in Ionic 2, how can we achieve the same functionality? I have tried using a button with a click event to print a console message but it is not working. <ion ...

Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the co ...

Having trouble implementing the ternary operator (?) in TypeScript within a Next.js project

Trying to implement a ternary operator condition within my onClick event in a Next.js application. However, encountering an error indicating that the condition is not returning any value. Seeking assistance with resolving this issue... https://i.stack.img ...

Create a Bar Graph Using a List

Looking to generate an Angular Barchart from a JPA query in Spring: public List<PaymentTransactionsDailyFacts> findPaymentTransactionsDailyFacts(LocalDateTime start_date, LocalDateTime end_date) { String hql = "SELECT SUM(amount) AS sum_volume, ...

Automating the scrolling function in Angular 2 to automatically navigate to the bottom of the page whenever a message is sent or opened

In my message conversation section, I want to ensure that the scroll is always at the bottom. When the page is reopened, the last message should be displayed first. HTML: <ul> <li *ngFor="let reply of message_show.messages"> ...