reactjsasp.netloggingcors

CORS Execution Policy Failed, Request Origin URL does not have permission to access the resource


I am trying to login by hitting the API : https://localhost:7252/api/auth/login from my React Frontend running on: http://localhost:3001/ . My login handling code for React Frontend :

const handleLogin = async () => {
    try {
      const response = await fetch("https://localhost:7252/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({
          Name: "se",
          Password: "0123456789",
        }),
      });
  
      if (!response.ok) {
        throw new Error(`Login failed! Status: ${response.status}`);
        console.log("shit");
        console.log(response.json);
      }
  
      const data = await response.json();
      console.log("Login Success:", data);
  
      // Optional: Store token if returned
      // localStorage.setItem("token", data.token);
    } catch (error) {
      console.error("Login error:", error);
      alert("Login failed. Please check the credentials or server.");
    }
  };

But I get shown in the logger which is in ASP.NET Backend: logger error

I tried enabling the CORs in my Program.cs file. This is my Program.cs file:

using Internship.DAL.Repositories;
using Internship.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();

// Configure Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>//line 14
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Internship API", Version = "v1" });

    // Configure Swagger to accept JWT tokens
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});

// Configure JWT Settings
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings"));

// Configure CORS for Blazor client
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins", policy =>
    {
        policy.WithOrigins(
                "http://localhost:3000" // React HTTP
             )
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
            .SetPreflightMaxAge(TimeSpan.FromSeconds(86400));
    });
});

// Configure JWT Authentication
var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jwtSettings.Issuer,
            ValidAudience = jwtSettings.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key))
        };

        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                // Accept token from either cookie or header
                context.Token = context.Request.Cookies["jwt_token"] ??
                               context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                return Task.CompletedTask;
            },
            OnAuthenticationFailed = context =>
            {
                Console.WriteLine($"Authentication failed: {context.Exception}");
                return Task.CompletedTask;
            }
        };
    });

builder.Services.AddAuthorization();

builder.Services.AddScoped<PersonRepository>();

var app = builder.Build();

// Configure the HTTP pipeline
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Internship API v1");
        c.OAuthClientId("swagger-ui");
        c.OAuthAppName("Swagger UI");
    });
    // app.UseHttpsRedirection(); // Optional during development
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
    app.UseHttpsRedirection();
}

app.UseStaticFiles();
app.UseRouting();

// IMPORTANT: Middleware order matters
app.UseCors("AllowSpecificOrigins");
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

This is my Network Tab: Netowk

I tried that in postman to login with the given credentials. It shows 200 OK . But when I try to login from my React Frontend, I get these errors. LoggingIn


Solution

  • Your CORS configuration in Program.cs seems correct. The issue likely comes from running multiple instances of your React app — one on port 3000 and another on 3001.

    You're using the instance on 3001 to make requests, but your backend is only configured to allow requests from http://localhost:3000. This mismatch triggers the CORS error.

    You have two options:

    Be consistent with the frontend port — Make sure you're running and accessing your React app only from the allowed port (e.g., 3000).

    Temporarily allow all origins (only during development) by configuring CORS like this:

    
    builder.Services.AddCors(options =>
     {     options.AddDefaultPolicy(policy =>
         {         policy.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();     });
     }); 
    

    Just be sure to remove or restrict this in production for security reasons.