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

Streamlined method for creating forms and charts within SharePoint

When it comes to creating charts and forms on SharePoint, what is the best approach for maximizing efficiency? Using AngularJS web parts with CRUD operations. Modifying standard forms and integrating charts using JavaScript libraries and CSS. Are there ...

Managing different data types in a single event emitter using Typescript: how do you approach it?

I'm currently working on a TypeScript function that detects the "Enter" key press and, if the event.target.value's length is greater than 0, redirects to a page with that value. This code snippet is being used in a Next.js application, hence the ...

Encountering a type error with gatsby-plugin-dark-mode in a Typescript Gatsby setup

Issue with Layout warning in index.tsx when hovering: (alias) const Layout: ({ children }: Props) => JSX.Element import Layout Type '{ children: Element[]; }' is missing the following properties from type 'Props': theme, >toggle ...

After a recent deployment, the Angular PWA hosted on a NestJS server experiences unexpected crashes

I have set up an Angular PWA (version 11) on a NestJS (version 7) server. However, after each new deployment, the PWA crashes because the browser attempts to fetch a JavaScript file that no longer exists and then redirects to the root site (html): main.945 ...

Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest. W ...

How is it that void can be assigned undefined?

According to the documentation on typescript, it states that "the one exception being that undefined is also assignable to void". Source Strict null checking mode specifies that null and undefined values are not within the domain of every type and can o ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Leverage custom attributes for user input in Ionic 2

Trying to incorporate custom attributes into inputs and divs has been a challenge for me. At first, when I hardcoded the data like this: <input type="hidden" class="test" value="0" custom-data='12345' /> everything worked perfectly. Howev ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

Using templateUrl from a remote server in Angular 2 can be achieved by specifying the complete URL

My file contains the following component with a remote URL: @Component({ templateUrl: '/mobilesiteapp/template/?path=pages/tabs' }) export class TabsPage { } Unfortunately, when compiling, I encountered this error message: [13:28:50] Error ...

Exploring the integration of an Angular 4 application with Visual Studio 2017 using dot net core. Techniques for accessing configuration keys from appsetting.json in a TypeScript

I'm currently working on an Angular 4 application using Visual Studio 2017 with .NET Core. I need to figure out how to access configuration keys from appsetting.json in my TypeScript file. I know how to do it in the startup.cs file, but I'm strug ...

Tips for incorporating runtime configuration into an Angular module and effectively leveraging it

After setting up Apollo Angular, I encountered a challenge in src/app/graphql.module.ts src/app/graphql.module.ts import { NgModule } from '@angular/core'; import { APOLLO_OPTIONS } from 'apollo-angular'; import { ApolloClientOptions, I ...

Slim 4 with Angular 10: Issues with downloading PDF files through API, as Angular blob response is coming back empty

Struggling to integrate the download PDF Angular API with Slim 4 API. The response from Slim can be seen in the browser network, but when trying to parse it in Angular, it comes back empty. All the necessary headers have been added on both Angular and Slim ...

Accessing the NestJS DI container directly allows for seamless integration of dependency

I have been using NestJS for the past 4 months after working with PHP for 5 years, mainly with Symfony. With PHP, I had the ability to access the compiled DI container and retrieve any necessary service from it. For example, in an application with service ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

Best Practices for Variable Initialization in Stencil.js

Having just started working with Stencil, I find myself curious about the best practice for initializing variables. In my assessment, there seem to be three potential approaches: 1) @State() private page: Boolean = true; 2) constructor() { this.p ...

How can a parent component update a child component's prop value in VUE?

I'm facing an issue with managing dynamic props in Vue with TypeScript. Below is my parent component: <script setup lang="ts"> const friends = [ { id: "emanuel", name: "Emanuella e", phone: "08788 ...

Tips on creating an object within a TypeScript interface

As a newcomer to Type Script, I am curious if there is a way to specify in the interface "IIndex" that SystemStatus is an object with properties Data and DataUrl. Currently, it appears that SystemStatus is undefined. interface IIndex extends ng.IScope { ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

When null is assigned to a type in Typescript, it does not result in an error being triggered

Could someone enlighten me on why this code is not causing an error? import { Injectable } from '@angular/core'; interface Animal{ name: string; } @Injectable() export class AnimalService { lion: Animal = null; constructor() {} get(){ ...