Unauthorized Token Authentication in .NET and Angular Application

Encountering an issue with user authentication. Login is successful and I receive a token from the API, which I save in JwtTokenService within my Angular App. When making a request (e.g. Delete), I add the "Authorization" header with the value "Bearer token", as I did previously in Postman. The client's request:

https://i.sstatic.net/BIaCX.png

However, I am receiving a 302 status code and being redirected to Account/Login even though such a route does not exist.

https://i.sstatic.net/U8a5b.png

Error message displayed in the console:

Access to XMLHttpRequest at 'https://localhost:44332/api/car/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Interestingly, GET requests (which have [AllowAnonymous] attribute) are working fine.

The request in Postman functions properly, leading me to believe there may be an issue related to cookies.

.Net Conf details:

[Route("api/[controller]")]
[ApiController]
[Authorize]
[ExceptionHandlingFilter]
public class CarController : ControllerBase
{


    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        
    }

Startup configuration snippet:

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
        });

 services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = configuration["Jwt:Issuer"],
                ValidAudience = configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]))
            };

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var accessToken = context.Request.Query["access_token"];
                    
                    // If the request is for our hub...
                    var path = context.HttpContext.Request.Path;
                    if (!string.IsNullOrEmpty(accessToken) &&
                        (path.StartsWithSegments("/chat")))
                    {
                        // Read the token out of the query string
                        context.Token = accessToken;
                    }
                    return Task.CompletedTask;
                }
            };
        });
        
app.UseCors("CorsPolicy");

EDIT1:

 [HttpDelete("{id}")]
    [Authorize(Policy = JwtBearerDefaults.AuthenticationScheme)]
    public async Task<IActionResult> Delete(int id)
    {

Error reported: System.InvalidOperationException: The AuthorizationPolicy named: 'Bearer' was not found.

Additional console error given below:

Access to XMLHttpRequest at 'https://localhost:44332/api/car/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. zone-evergreen.js:2845 DELETE https://localhost:44332/api/car/2 net::ERR_FAILED

Answer №1

Below is an example of how to implement CORS in your application.

Solution
In your startup file, make the following additions:

services.AddCors(options =>
{
    options.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin();
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
    });
});

app.UseRouting();

app.UseCors();

app.UseAuthorization();
...

Add the following code snippet to your controller file.

[ApiController]
[Route("[controller]")]
// <Mainly just need to add the below attribute>
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
// </Mainly just need to add the below attribute>
public class WeatherForecastController : ControllerBase
{
    [HttpPost]
    [Route("PostRequest")]
    public IActionResult PostRequest(string parameter)
    {
        return Ok(new { result = parameter });
    }
}

Client Side

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with 
ASP.NET Core</a>.</p>
</div>

<script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>
<script>

    $(document).ready(() =>{
        $.ajax({
            type: 'POST',
            url : 'https://localhost:44304/weatherforecast/PostRequest?parameter=someValue',
            contentType: 'application/json',
            success: function (data){
                console.log(data);
            },
            error: function (data){
                console.log(data);
            },
        });
    });
</script>

This setup should enable CORS for your application.

https://i.sstatic.net/6SdZW.png


If the

[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
attribute is removed from the controller, the functionality will not work as expected.

https://i.sstatic.net/dco2l.png



All the resources you require are available in the provided link and can be easily integrated into your project.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-attributes

Answer №2

When setting up your application in the Startup.cs file, make sure to include the following code in the ConfigureServices method:

 services.AddCors(options =>
 {
   options.AddPolicy("MyCustomPolicy", builder =>
   {
       builder.AllowAnyOrigin();
       builder.AllowAnyHeader();
       builder.AllowAnyMethod();
   });
});

Then, in the same startup file, add the policy name to configure it:

 app.UseCors("MyCustomPolicy");

If you want to use App.UseCors() without specifying a policy name, you can only do so if you have previously used .AddDefaultPolicy(...)

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

Implementing the same concept yet yielding diverse variations?

I'm a bit confused as to why a1 is evaluated as false while a2 is considered to be of type boolean. Can someone explain the reasoning behind this discrepancy? type Includes<T extends readonly any[], U> = U extends T[number] ? true : false; type ...

The compiler error TS2304 is indicating that it cannot locate the declaration for the term 'OnInit'

I successfully completed the Angular superhero tutorial and everything was functioning properly. However, when I close the CMD window running NPM and then reopen a new CMD window to reissue the NPM START command, I encounter two errors: src/app/DashBoard ...

Implementing Angular's Lazy loading feature can be achieved by loading a module within another module that has

In my Angular application, the main routing module successfully lazy loads modules. However, I now have a new requirement to include another component/module inside one of the lazy loaded modules. When navigating to users/id (which is working correctly), ...

Issue arises when integrating Angular 13 with ngrx and OAuth2: encountering difficulties in creating an effect

Currently, I'm following an example that uses an earlier version of Angular and ngrx. You can find the tutorial on NGRX Authentication in Angular with asp.net core here. This is what my Auth.action.ts file looks like: import { createAction, props } f ...

Obtain the SelectedValue from a Dropdownlist within a Gridview

How can I create a list of users in a Gridview who have not updated their job titles? The list should include a dropdown menu with all possible title selections and a button next to it. Users should be able to select a new title from the dropdown, click th ...

How can one obtain the alphabet letters of a specific language?

Is there a way to programmatically retrieve the alphabet of a language (using its 2-letter ISO code) from an open-source repository? For instance: console.log(getAlphabet('en')); would result in: a b c d ... while console.log(getAlphabet(&apos ...

Having issues with matSort functionality on mat-table in Angular

The content of my .html file is shown below: <mat-table [dataSource]="dataSource" padding matSort> <ng-container matColumnDef="uid"> <mat-header-cell *matHeaderCellDef mat-sort-header> Building UID </mat-header-cell&g ...

The class is not correctly implementing the 'OnInit' interface. The 'ngOnInit' property is missing in the 'Component' type, which is required in the 'OnInit' type

Could someone offer assistance with this issue? It seems like there are errors in the code structure: Class 'ContactFormComponent' incorrectly implements interface 'OnInit'. Property 'ngOnInit' is missing in type 'Contac ...

Execute GCC within Bash on Windows 10 using either C# or C++

Is there a way to execute gcc on bash using either C# or C++ in order to create a simple IDE? I attempted to run gcc with the command: bash gcc --version (where --version is just an example) but encountered the error: /usr/bin/gcc: /usr/bin/gcc: Can't ...

The Ajax UpdatePanel embedded within the repeater seems to be lacking the necessary post back

I am facing an issue with postback of the UpdatePanel inside the repeater. <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:Repeater ID="Posts" runat="server" OnItemCreated="Posts_OnItemCreated"> <I ...

Verify whether the user is authenticated in Angular 2

For the past couple of days, I've been struggling with figuring out how to determine if a user is authenticated in my Angular-rc1 application and could really use some assistance or guidance. After receiving a token from the server, I want to save it ...

Can *ngFor in Angular handle asynchronous rendering?

Within the code snippet provided, the line this.images = response.map( r => r.url).slice(0,10); populates the images array. The data is then rendered in the view using ngFor. Following this, a jQuery function is invoked to initialize an image slider. Ho ...

Saving a list of generic items in cookies

I am looking for a way to persist my generic list in cookies instead of relying on session storage, which keeps expiring whenever I make code changes and rebuild. I want to ensure that my list remains intact even after rebuilding by storing it in cookies. ...

How to send all items from a listbox to a controller in MVC 5

Having an issue passing all items in a listbox back to the controller. The controller remains empty even when I declare another variable for it as List. It only passes back the selected value, but I want to pass back all values. I am working with 2 listbo ...

Is it possible to attain the identical user experience using ASP.NET MVC as with ASP.NET (Webforms)?

Similar Question: Can ASP.NET MVC be integrated with regular ASP.NET Web forms Imagine I'm tasked with creating a shopping cart. Would ASP.NET MVC provide the same level of user experience as traditional Webforms, or is it better to use both tool ...

Selenium: Timeout in clicking to open a modal dialog box

My current task involves automating an editor within a CMS, offering various options such as adding links and changing text colors. The challenge I'm encountering is that when clicking a toolbar button, a JavaScript command triggers a modal dialog bo ...

The task completion resulted in exit code -2146233082

I'm facing an issue with my C# .NET 4.5 project. During the build process, a custom build-task gives me this error message: The command ""C:\Program Files (x86)\Microsoft\Contracts\Bin\ccrefgen.exe" "@obj\Debug\Data ...

Angular 8: Bridging the gap between two players with a shared singleton service

I've been working on creating a multiplayer Battleships game, and although the basic functionality is there, I'm struggling to connect two players to the same game. Any assistance would be greatly appreciated! My goal is to create a service that ...

Parsing poorly formatted data structures using JSON.NET

Due to reasons outside my control (the SurveyGizmo API), I must unpack data stored in the following (example) layout: // JSON data formatted by API [{ "id": "2", "contact_id": "", "status": "Deleted", "is_test_data": "1", "datesubmitte ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...