Using an Angular HttpClient to authenticate with an API by utilizing a token for

I am currently attempting to fetch data from my Jenkins JSON API via HTTPClient. The data I need access to is restricted, so I must authenticate against Jenkins. To do this, I have generated an API Token. However, I am unsure of how to authenticate myself using the Angular HTTPClient.

Could someone offer assistance with my issue?

Thank you

Answer №1

If you want to include extra headers with all your outgoing http requests, you can take advantage of the HttpInterceptor.

@Injectable({
  providedIn: 'root'
})
export class OutgoingInterceptor implements HttpInterceptor {



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

     interceptedRequest = req.clone({
         setHeaders: {

             // These headers are specifically for Passport authentication.
             // You may adjust these according to your requirements
             // Remember to securely store your token, for example in localStorage

             Accept: 'application/json',
             Authorization: tokenData
         }
     });

     return next.handle(interceptedRequest);
  }
}

Lastly, make sure to add this newly created interceptor to the provider array of your module:

providers: [

    ... 

    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
]

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

Transform a JSON string into C# objects

Let me keep this brief and to the point. I receive a JSON string from a public API that contains data about transportation lines. Here is a snippet of the JSON: [{ "$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities", "id": ...

Error compiling SCSS in Angular 6 due to a util.js issue

As a novice in the world of Angular 6, I am currently exploring the Angular CLI and trying to grasp the file structure. My goal is to utilize SCSS for creating a unified global stylesheet. However, during compilation, an error keeps popping up: ERROR in . ...

"Implementing Two-Way SSL with Angular 2 and BrowserSync

Currently, I am working on an Angular2 application that requires two-way SSL authentication. This means that the browser needs to present a valid (PFX) certificate in order to access the application. For deployment, I am using lite-server (which utilizes B ...

Angular CLI - managing separate development and production assets

Is there a way to switch to a different set of assets when using the --prod flag with ng build? In my scenario, I have multiple projects that share a common set of assets in a designated folder. Each project's configuration in angular.json looks simi ...

Should we be worried about the security of the RxJS library?

Currently, I am in the midst of a project utilizing RxJS within the Angular framework. A recent security evaluation flagged the use of window.postMessage(‘’, ‘*’) in our application as a potential vulnerability. Further investigation pinpointed Imm ...

What is the method for generating an observable that includes a time delay?

Question In order to conduct testing, I am developing Observable objects that simulate the observable typically returned by an actual http call using Http. This is how my observable is set up: dummyObservable = Observable.create(obs => { obs.next([ ...

Can @Input() be declared as private or readonly without any issues?

Imagine you're working in an Angular component and receiving a parameter from its parent. export class SomethingComponent implements OnChanges { @Input() delay: number; } Would it be considered good practice, acceptable, or beneficial to designat ...

Navigating from a library to app components: A step-by-step guide

I successfully converted my login-component into a library, and now the first thing displayed in myApp is the login page. However, I'm facing an issue with navigating to the home page after a successful login. Can anyone provide guidance on how I can ...

Show a table row based on a specific condition in Angular

I'm having this issue with the tr tag in my code snippet below: <tr *ngFor="let data of list| paginate:{itemsPerPage: 10, currentPage:p} ; let i=index " *ngIf="data.status=='1'" > <td> </td> <td> ...

Angular Version 11 is throwing a NullInjectorError with the message: "No provider found for Control

I recently implemented a custom input component based on the guidance provided in this interesting article: medium.com: dont-reinvent-the-wheel. Below is the code snippet I used, written in strict mode ▼ // input.component.ts import { Component, Input, ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

Check my Twitter feed every 10 seconds

I'm attempting to access my Twitter feed (sent from a smartphone) for a local application, as Twitter is remote... I created a jQuery + JSON script, but with my overly frequent setInterval at 25ms, I quickly hit the limit of 150 requests per hour and ...

What is the reason behind Angular's renderer.listen() causing the text to be deselected?

(Background: my project involves developing an email processor that displays emails on a web page) To enable click events in a specific area, I leverage Angular's Renderer2. This approach is necessary because the content is dynamically generated with ...

Creating folders and writing data to text files in Angular 4/5 with TypeScript: A tutorial

Is it feasible to create a folder, text file, and write data into that file in Angular5 using Typescript for the purpose of logging errors? Your expertise on this matter would be greatly appreciated. Thank you in advance! ...

Unable to access the HTTP POST response data beyond the .subscribe method

I am facing an issue with accessing data from a variable set after making an HTTP request to a server. The request returns the correct data as a response, but I am unable to access the variable data from another method. Below is my code snippet: public u ...

Encountering a 401 Error while using Laravel Sanctum/Airlock

Currently, I am utilizing Laravel as the back-end for my innovative Next JS application, with Sanctum being leveraged for authentication purposes. While session authentication operates smoothly on the front end, issues arise when attempting to send reque ...

Storing Global Types in Angular: A Better Approach

Imagine I possess certain universally applicable enums, interfaces, or extensive classes. For example: export interface LogMessage { code: number; message: string; } Where would be the optimal location to store them? What is considered the best pr ...

Avoiding loading certain images within an *ngFor loop

Is it possible to control the loading of images within an *ngFor loop in Angular? Load image with index X first Fire a function once all other images have loaded The goal is to prioritize the display of important images while optimizing bandwidth usage. ...

BackBlazeTokenResponse - Unrecognized Property Exception: The field "allowed" is not recognized

While attempting to retrieve a BackBlaze Authorization token, I encountered an error. Previously, everything was functioning as expected, but now I am receiving the following error message - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyExceptio ...

Creating a structured state declaration in NGXS for optimal organization

Currently, I'm delving into the world of NGXS alongside the Emitters plugin within Angular, and I find myself struggling to grasp how to organize my state files effectively. So far, I've managed to define a basic .state file in the following man ...