简体   繁体   中英

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

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.

邮递员截图

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM