Tips for including an authorization token in an HTTP request

I encountered a 401 unauthorized error when trying to access my REST endpoint, likely due to the security measures I have implemented. I suspect that there might be an issue with how I am handling the HTTP headers.

The application utilizes a Spring Boot backend REST API, which I know functions correctly. This is evident because when I obtain a token using Postman and then use that same authorization token in Postman to interact with the API, everything works smoothly.

getWeatherByCityAndCountry(city: string, country: string): Promise<Weather> {

    let headers = new HttpHeaders();
    headers = headers.append('Authorization', 'Bearer '+ this.accessToken);
    return this.http.get(this.baseUrl + '/byCity/' + city + '/' + country, {headers: headers})
      .toPromise()
      .then(response => response as Weather)
      .catch(this.handleError)
  }

The accessToken has been hardcoded with a token value obtained from Postman.

Answer №1

If you're looking to streamline the process of intercepting requests in Angular, my recommendation is to implement an interceptor that captures all requests automatically rather than manually adding them each time.

import {
  Observable
} from 'rxjs';
import {
  Injectable
} from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest
} from '@angular/common/http';

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
    const responseType = req.responseType || 'json';
    const apiToken = localStorage.getItem('Authorization');
    const authed = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + apiToken),
      responseType
    });
    const notAuthed = req.clone({
      responseType
    });
    const modifiedReq = apiToken ? authed : notAuthed;

    return next.handle(modifiedReq);
  }
}

To integrate this interceptor into your project, add the following configuration to your module providers array:

{
      provide: HTTP_INTERCEPTORS,
      useClass: CustomHttpInterceptor,
      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

Resize the textarea to fit a maximum of five lines, and display a scrollbar if necessary

Explanation: I am facing an issue in Angular 2 regarding the chat screen. I need the chat screen to dynamically increase in size as I type, up to a maximum of 5 lines, and then show a scrollbar. How can I achieve this functionality? Problem: The current b ...

Is it possible for me to assign an observable to a value of undefined or null?

In my Angular class, I have an observable setup like this: fullMember: Observable<Member | undefined> and in the constructor: this.fullMember = store.pipe(select(selectActiveMember)) From this selection, I'm extracting certain information ...

unable to assign an array to a different array in typescript

I'm facing an issue with assigning values to the private kitems array in my class. Despite defining it as kitems:any[], when I try to assign a value using this.kitems = items; and then log this.kitems, it shows up as an empty array. createprofile() { ...

Having trouble setting up the calendar feature in my Ionic Angular application

I have a simple task at hand: creating a project for a calendar/schedule app that displays and allows editing of the schedule/division of professors in my institute on a daily basis. First off, do you have any better ideas, methods, or software suggestion ...

Surprising Logging Quirks in Angular

I've encountered a perplexing issue in my Angular app where an array is logged before adding an element to it, yet the log shows the updated array with the added element. This array is then utilized in an HTML file with ngFor. component.ts file inter ...

conceal a div in Angular when the user is authenticated

One of my tasks involves managing the visibility of a div based on whether the user is logged in. This functionality is achieved by utilizing an authentication service in Angular and tokens from Django. Component.html <a *ngIf="authService.isLoggedIn( ...

What is the best way to perform type checking for a basic generic function without resorting to using a cumbersome cast

Struggling with TypeScript and trying to understand a specific issue for the past few days. Here is a simplified version: type StrKeyStrVal = { [key: string]: string }; function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: str ...

What is the process for switching views by tapping on a button?

Currently, I am working on a registration form that consists of 3 steps. I need to change the view of the form to another view when clicking the Next button. I have been attempting to achieve this in Angular 2 by using routing, but it seems to be replacin ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

Tips for fixing a GET 404 (not found) error in a MEAN stack application

While working on a profile page, I encountered an error when trying to fetch user details of the logged-in user: GET http://localhost:3000/users/undefined 404 (Not Found) error_handler.js:54 EXCEPTION: Response with status: 404 Not Found for URL: http:// ...

Encounter an issue while running the angular build in production mode

Encountering an error stating "Type src/app/createreportcomponent component.ts is part of the declarations of 2 modules" while the normal development build is running smoothly. How can this error be resolved? ****App Module ts file**** import { BrowserMo ...

Establishing a secure connection between Spring Boot data and a database with certificate authority verification

Attempting to connect to the Postgresql database over SSL, I have encountered an issue. I placed the certificate files in both the resources folder and another directory, but I am getting the error message "java.io.IOException: extra data at the end." Int ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

What methods can I use to locate the circular dependency within my program?

I am facing numerous circular dependency errors in my Angular project, causing it to malfunction. Is there a way to identify the section of the code where these circular dependencies exist? Warning: Circular dependency detected: src\app&bs ...

Angular's $location is reverting back after the modification

When using Angular, I encountered an issue where the user was not redirected to the view page after submitting a form. To handle this, I attached the following function to the scope: $scope.create = function () { return $scope.customer.$save({}, funct ...

What steps should I follow to implement Cypress in an older project?

Looking to automate a project built with Node.js version 8.9.4 and an older version of Angular using Cypress for testing, but running into compatibility issues with the current version of Cypress. Is there a way to use an older version of Cypress in this ...

Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error. le ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Angular 2 offers the ability to crop and save images effortlessly

Utilizing ngImgCrop, I have been able to upload images and crop them successfully. Now, I am trying to figure out how to save the result-image from <img-crop image="myImage" result-image="myCroppedImage"></img-crop> to a folder in ASP.NET MV ...

What improvements can I make to enhance my method?

I have a block of code that I'm looking to clean up and streamline for better efficiency. My main goal is to remove the multiple return statements within the method. Any suggestions on how I might refactor this code? Are there any design patterns th ...