Implementing authentication using JWT in .NET Core and Angular 7: A comprehensive guide

The startup file for .NET Core 2.2 has been configured as shown below:

var key = Encoding.ASCII.GetBytes(AppSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = 
 JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

Within the configure method:

app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseMvc();

I am utilizing .NET Core APIs in my Angular 7 SPA application and making calls to my API method:

this.http.get<User>(path + 'api/' + 'users', { withCredentials: true })

However, upon initial access of the Angular application, the API call fails with a 401 error in the logs. The network tab shows the status as (failed), but upon reloading the application, it works. This error seems to occur randomly, and can be reproduced when attempting to access the application in incognito mode.

This issue only arises on deployed applications on Windows web servers where Anonymous and Windows authentication are both enabled.

No changes have been made to program.cs, which remains at the default configuration for .NET Core 2.2.

Despite extensive research and trying various suggestions found online, none have provided a solution. Is there another area I should investigate?

Answer №1

It is essential to include the token in the header when sending it to an asp.net core controller so that the server can identify you.

Save the token in the localStorage and then add it to the header for authentication purposes.

Update:

Consider modifying your code as shown below to check if it resolves the issue

this.http.get<User>(path + 'api/' + 'users')

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

There was a server error in the application, with the message: "Key cannot be null. Parameter name: key."

Every now and then, I encounter a problem when trying to generate a report using stimulsoft: Key cannot be null. Parameter name: key Description: An unhandled exception occurred during the execution of the current web request. Please review the stack tr ...

Establish a connection between an Angular Docker container and an Asp.Net container

A program was developed with three main components: a database (MS SQL Server), backend (Asp.Net Core), and frontend (Angular 8). The program is run using docker-compose: services: sqlserver: image: mcr.microsoft.com/mssql/server:2019-latest ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

Trigger the Modal once the navigation step is completed

When navigating to a new page, I need to wait for the navigation process to complete in order for the modal template to be properly displayed on the destination page. public onOpenModal(item) { this.router.navigate([item.link]).then(() => { this. ...

Tips for consolidating specific user data into a single row

If I have a table with the following structure: serial regnum value type 1 55 100 normal 2 55 66 Light 3 77 70 normal 4 30 40 Light What is the SQL query or LINQ ...

Recover the node modules directory

By mistake, I deleted the MyProject/node_modules directory from my solution. Is there a way to recreate this folder? I attempted running npm install and npm update, but had no luck. ...

Getting rid of parameters in HttpParams in Angular 4.3

I am working with a HttpParams object that looks like this: private filter: HttpParams = new HttpParams(); [...] this.filter = this.filter.append('page','1'); this.filter = this.filter.append('pageSize','50'); this. ...

guide on setting output parameter for mysqldataadapter

Struggling with defining p_maxsi as an output parameter in .NET for MySqlDataAdapter. MySqlDataAdapter msdadapter = new MySqlDataAdapter("usp_NewItemId_test", mysqlcon); msdadapter.SelectCommand.CommandType = CommandType.StoredProcedure; msdadapter.Sel ...

Validation of emails in Angular through the utilization of reactive forms

Hello there, I'm new to Angular and looking for some assistance. Specifically, I am currently working on validating an email input using a reactive form with the keyup event. registerform:any; ngOnInit(): void { this.registerform = new F ...

retrieving a date from a different source and displaying it in a date

Is there a way to ensure that the date format in an input of type date always follows the dd/MM/yyyy Brazilian pattern, regardless of the computer or browser specifications? <div class="input-group input-group text-center in ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

Is it possible to open a link in a webBrowser control using an external browser?

In my Windows Forms application, I have implemented a functionality where a user can input HTML code into a textBox and see its compiled form in a webBrowser control. I achieved this by using the following code: private void textBox2_TextChanged(object se ...

Developing a firestore query using typescript on a conditional basis

I've encountered an issue while attempting to create a Firestore query conditionally. It seems like there's a TypeScript error popping up, but I can't seem to figure out what's causing it. Here's the snippet of my code: const fetch ...

Combining Two Related API Requests using Angular Observables and RxJS

If I have two API calls that return JSON: First call (rows): { {"row": 1, detailId: "a"} {"row": 2, detailId: "b"} } Second call (rowDetails): { details: { row details } } The task at hand is to fetch rows first, then iterate through each row o ...

Tips for transferring information from Angular 6 to Node.js

Having recently delved into Angular 6 for the first time, I find myself tasked with sending data to a Node.js server. The code snippet below illustrates my approach within an Angular function: import { Component, OnInit } from '@angular/core'; ...

Is there a way to automatically validate v-forms inside a v-data-table when the page loads?

In my data entry form, I have utilized a v-data-table with each column containing a v-form and v-text-field for direct value updates. My goal is to validate all fields upon page load to identify any incorrect data inputs. However, I am facing challenges in ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Is it feasible to utilize Progressive Web Apps on the Angular development server (ng serve)?

Recently, I've been diving into a new project where I'm exploring PWA for the first time and experimenting with push notifications. So far, I've managed to get PWA up and running by running the commands ng build --prod and http-server -p 80 ...

Exploring methods for efficiently handling extensive XLSX files in a Node.js environment

Currently, I am utilizing the ts-xlsx library on the server side to read data. The process involves reading data from the frontend as a byte array using file-reader and then sending this byte array to a library to process the data. However, in cases where ...