Embed a JSON Web Token into an API call using Angular 4

I have successfully integrated JWT login into my Angular app with ASP.NET Core 2.0 back-end. Now, I am facing an issue when trying to fetch data for resources requiring authorization via JWT, following a tutorial. The HTTP get works fine in Postman using the token, but in my Angular app I receive a 401 error.

The server API call is defined within the SampleDataController class:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
public class SampleDataController : Controller
{
    // Code for WeatherForecasts method here...
}

My Angular component code looks like this:

// Angular code for FetchDataComponent here...

interface WeatherForecast {
    dateFormatted: string;
    temperatureC: number;
    temperatureF: number;
    summary: string;
}

Additionally, below is the code snippet responsible for adding the authorization header:

// TokenInterceptor class implementation here...

Any assistance on resolving the authorization issue would be greatly appreciated.

Answer №1

There was an issue that needed fixing:

   Authorization: `Bearer ${this.auth.getToken()}`

Initially, the getToken method was returning the entire Token object. However, a helpful suggestion from another user led me to explicitly extract the actual token string in this manner:

JSON.parse(localStorage.getItem('token')).token

Following this adjustment, my problem was successfully resolved.

Answer №2

It's quite straightforward, the tutorial you shared utilized angualar-jwt (which I've also used).

They offer their own http service wrapper that includes a stored JWT token in the request to your API endpoint or another one.

If it's a different API, ensure to adjust the header prefix to match where they expect the JWT token.

As stated in the angular2-jwt readme:

If you want to send a JWT only on certain HTTP requests, you can utilize the AuthHttp class. This class is an Angular 2 Http wrapper and supports all standard HTTP methods.

import { AuthHttp } from 'angular2-jwt';
// ...
class App {

thing: string;

constructor(public authHttp: AuthHttp) {}

getThing() {
    this.authHttp.get('http://example.com/api/thing')
    .subscribe(
        data => this.thing = data,
        err => console.log(err),
        () => console.log('Request Complete')
    );
}
}

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

Issue updating Bootstrap in ASP.Net Core 2.1 with Angular Template

Every time I start a new ASP.Net Core 2.1 project with the angular template and try to update the bootstrap version from 3 to 4 in package.json, it ends up breaking my application. Despite numerous attempts such as deleting the node_modules folder and rein ...

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

typescript code may not display a preview image

I recently came across a helpful link on Stack Overflow for converting an image to a byte array in Angular using TypeScript Convert an Image to byte array in Angular (typescript) However, I encountered an issue where the src attribute is not binding to t ...

What are the solutions to resolve this error in C# ASP LINQ?

Just moments ago, this section of my code was running smoothly. However, in a sudden turn of events, I encountered an issue when compiling the project. Here is the snippet of code causing trouble: string Cat = ddlCategoria.SelectedValue; int? Max ...

What could be the reason why my focus and blur event listener is not being activated?

It seems like everything is in order here, but for some reason, the event just won't fire... const element = (this.agGridElm.nativeElement as HTMLElement); element.addEventListener('focus', (focusEvent: FocusEvent) => { element.classLi ...

The TypeScript find() method on an array are showing an error message that says, "There is no overload that matches this call

Issue Description I encountered a problem while using TypeScript's find() method for an array. Whenever I input a value, it does not work properly and displays an error message stating, "No overload matches this call". Code Snippet addOption(event: ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

What is the best way to convert an enum into an array containing all the values of its items in TypeScript?

For example, consider the following TypeScript enum: export enum UserType { Guest = 1, SNS = 2, Account = 3, Certified = 4, } Is there a way to dynamically create an array with specific values without hard-coding them? const atrrib ...

The type of JSX element attribute `[...]` cannot be a combination of multiple types

When attempting the codes below in Typescript 2.1: // address.tsx ... interface Address { street: string; country: string; } interface CanadianAddress extends Address { postalCode: string; } interface AmericanAddress extends Address { zipCode: s ...

Capturing user input with Angular Material forms in HTML

In the process of working on a project in Angular, I am utilizing the Angular Material component library. As part of this project, I am creating a form with multiple fields. Everything is functioning properly, however, the layout appears slightly off: ht ...

Exploring the power of Vue3 with reactive nested objects and the inclusion of

It seems like I've encountered a bit of a challenge... Perhaps a bug in Vue3 with Typescript and the composition API, or maybe I'm missing something. I'm facing an issue where I'm not getting any intellisense in my IDE (Webstorm) when ...

I need help differentiating "namespace" from "static attributes" in TypeScript

Separating namespace from static properties in TypeScript can sometimes be tricky. error: 'ClassA' only refers to a type, but is being used as a namespace here. class ClassA { static ClassB = class { }; } type T = ClassA // ok type T = C ...

Unable to find values for all parameters on the ContactEdit page

While exploring the functionality of local storage, I encountered an error when trying to inject it into my constructor: 'Can't resolve all parameters for ContactEdit page ?, [object Object], [object Object], [object Object], [object Object] ...

Tips for updating the Gridview's Header Text following DataBinding

I am facing an issue with a dynamic GridView that is bound to a DataTable. The text in the design contains underscores ('_') which I want to replace with spaces. I have tried changing it after databinding and in the PreRender event of the gridvi ...

Display "No Results Found" in Angular and Ionic 4 when the observable is empty

Below is the HTML code: <ion-list> <ion-radio-group> <ion-item class="ion-no-padding" *ngFor="let service of services | async"> <ion-label> <ion-grid> <ion-row> < ...

In Express, the async middleware is bypassed, allowing the next route to be executed seamlessly

Currently, I am in the process of developing an application similar to Zotero using express.js, but I have encountered a perplexing issue. Although I cannot pinpoint the exact problem, based on the logs I am receiving, it appears that my middlewares are n ...

Best practices for securely storing access tokens in React's memory

I'm on a quest to find a secure and efficient way to store my access token in a React application. First and foremost, I have ruled out using local storage. I don't see the need to persist the access token since I can easily refresh it when nece ...

Encountering Error: Unable to bind EventEmitter as it is not recognized as a valid property in Angular 8

I have been struggling with using EventEmitter in Angular and I can't seem to get it right. I'm new to Angular and it's all a bit confusing for me. I've checked other posts and it seems like I'm doing everything correctly! I'm ...

Verifying a data field in a document in Cloud Firestore for a particular value

Is there a way to validate the existence of a username in my Users Collection before allowing user registration? The usernames are stored on user documents in Firestore. https://i.stack.imgur.com/WARAs.png I'm looking for a snippet or solution that ...