CORS how to allow preflight requests with IIS Express VS Debugger and with credentials (authentication)
Asked Answered
V

0

3

I have enabled CORS as follows

Program.cs

builder.Services.AddCors();

var app = builder.Build();
 
app.UseRouting();

app.UseCors(x => x.AllowAnyMethod().AllowAnyHeader().AllowCredentials().SetIsOriginAllowed(origin => true));
 
app.UseAuthentication();

Client

const axiosClient = axios.create({
   baseURL: configuration.apiUrl,
   headers: { "Content-type": "application/json" },
   withCredentials: true });

Server (LaunchSettings.json)

 "CustomProfile": {
      "commandName": "IISExpress",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:60737",
      "sslPort": 44358
    }
  }

When I call

// Get records list
axiosClient.get('records').then((res: AxiosResponse) => res.data)

I get Status Code 200 with the data and the user was authenticated at the backend.

But when I call

// Create new record
axiosClient.post('record', createCommand).then((res: AxiosResponse) => res.data)

I get following error message

Access to XMLHttpRequest at 'https://localhost:44358/api/records' from origin 'https://localhost:44414' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

any idea what might be wrong and how to fix it?

Voidable answered 5/9, 2023 at 14:24 Comment(2)
Preflight requests are anonymous, so Windows authentication simply blocks all of them and leads to the issue. You have to use IIS CORS module on IIS or IIS Express to handle that properly.Mars
IIS Express is started from Visual Studio. How to enable anonymous preflights? When I setup "anonymousAuthentication": true, than the authentication is not done at all.Voidable

© 2022 - 2025 — McMap. All rights reserved.