0

I have a simple webservice written in .NET Core 6 which is being accessed by a react application. Every call returns a CORS error: Access to XMLHttpRequest at 'https://localhost:7023/api/auth/login' from origin 'https://azmeits1:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is the code from Program.cs of the webservice:

builder.Services.AddDbContext<WpmDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddCors(); 

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

//app.UseRouting();
app.UseHttpsRedirection();

app.UseCors(x => x
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader());

app.UseAuthentication();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
app.Run();

I know the order of events matter but no matter what I try I end up with the same CORS error in the deployment environment.

Ive tried swapping it around for:

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins, policy =>
    {
        policy
        .SetIsOriginAllowed(origin => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
    });
});

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

//app.UseRouting();
app.UseHttpsRedirection();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthentication();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
app.Run();

Not sure if it makes a difference but the Controller code looks like this:

namespace TestAPI.Controllers
{
    [Route("api/auth")]
    [ApiController]
    [Authorize]
    public class AuthController : ControllerBase
    {
        [HttpPost("login")]
        [AllowAnonymous]
        public ActionResult<string> Login([FromBody] UserDto request)
        {
            //login code
        }
    }
}


dprozorov
  • 21
  • 3
  • Regardless of your issue, never use `SetIsOriginAllowed(origin => true)` with `AllowCredentials()`. It's wildly insecure. – jub0bs Mar 10 '23 at 07:42

1 Answers1

0

For testing purpose, I created a .net 6 api project and I added your codes to program.cs file. However, I didn't reproduce your issue. But if I use IIS Express mode to run the api project then test it, I got the same error message in browser. So you can try to set the value "anonymousAuthentication" as true to fix the issue. You can check this:enter image description here

If this doesn't help you, you can try this answer.

Xiaotian Yang
  • 499
  • 1
  • 2
  • 7