Home > Net >  Disable Access-Control-Allow-Origin in ASP.Net and ASP.Net Core
Disable Access-Control-Allow-Origin in ASP.Net and ASP.Net Core

Time:05-28

We just had an external pen test and all of our sites are coming back with a low warning stating that we allow cross site scripting. I don't think this is actually the case since we had to specifically allow it on one page on one specific site for that one to work.

The report shows that when calling our URL's a header for Access-Control-Allow-Origin is set to *. Using Postman I can get that same result.

PostMan Screenshot

This is returning the same result from both ASP.Net web forms applications as well as new ASP.Net 6 Razor page apps. Is there any way to have this header removed? Maybe something in IIS?

CodePudding user response:

To get rid of it you have to list all the origins that are allowed to send the requests to your endpoint. If you are running ASP.NET Core application then you have to configure the CORS middleware like this:

// Startup.ConfigureServices() method

// For example only, put these values in the appsettings.json so they could be overridden if you need it
var corsAllowAnyOrigin = false;
var corsAllowOrigins = new string[]{ "https://*.contoso.com", "https://api.contoso.com" };

// Configuring CORS module
services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            if (apiConfiguration.CorsAllowAnyOrigin)
            {
                builder.AllowAnyOrigin();
            }
            else
            {
                builder.WithOrigins(apiConfiguration.CorsAllowOrigins);
            }

            builder.AllowAnyHeader();
            builder.AllowAnyMethod();
        });
});

For your Web Forms application you can install IIS CORS module and configure it in the web.config file like this:

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <cors enabled="true">
      <add origin="*" allowed="false"/>
      <add origin="https://*.contoso.com" allowCredentials="false" />
      <add origin="https://api.contoso.com" allowCredentials="true" />
    </cors>
  </system.webServer>
</configuration>
  • Related