Cross-Origin Resource Sharing (CORS)

  • 3 minutes to read

On the web, you need to set up cross-origin resource sharing (CORS) on your back-end to configure corresponding permissions to access resources from a server at a different origin.

The Web Dashboard Control uses a JSON contract between server and client. According to Hypertext Transfer Protocol (HTTP/1.1) standard, the Web Dashboard control adds the Content-Type: application/json HTTP header for each post request. If you use CORS in your application, you should set Content-Type as an allowed header.

Enable CORS for ASP.NET Core

IMPORTANT

The Microsoft.AspNetCore.Cors NuGet package is required for the ASP.NET Core Dashboard server.

CORS Middleware handles cross-origin requests. You can configure CORS in the Startup.cs file.

Create CORS Policies

The AddCors method call adds CORS services to the app's service container.

As a simple way to configure CORS policy, you can call the AllowAnyOrigin method to allow CORS requests from all origins with any scheme (http or https). AllowAnyOrigin is insecure because any website can make cross-origin requests to the app.

public void ConfigureServices(IServiceCollection services) {
    services
        .AddCors(options => {
            options.AddPolicy("CorsPolicy", builder => {
                builder.AllowAnyOrigin();
                builder.AllowAnyMethod();
                builder.WithHeaders("Content-Type");
            });
        });
    // ...
}

The better way is to specify the client application's URL directly to prohibit any client from getting access to your server with personal info. You can also configure the allowed HTTP methods and request headers. Use the WithOrigins, WithMethods, and WithHeaders methods to set it up:

public void ConfigureServices(IServiceCollection services) {
    services
        .AddCors(options => {
            options.AddPolicy("CorsPolicy", builder => {
                builder.WithOrigins("https://example.com");
                builder.WithMethods(new String[] { "GET", "POST"});
                builder.WithHeaders("Content-Type");
            });
        });
    // ...
}

Enable CORS for Routing at MVC Level

For routing at the MVC level, call UseCors before the UseMvc method and pass the policy name as a parameter:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    // ...
    app.UseCors("CorsPolicy");
    app.UseMvc(routes => { ... });
}

Enable CORS with Endpoint Routing

With endpoint routing, call UseCors before the UseEndpoints method and pass the policy name as a parameter. Then call the RequireCors method with the same policy name:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    // ...
    app.UseCors("CorsPolicy");
    app.UseEndpoints(endpoints => {
        EndpointRouteBuilderExtension.MapDashboardRoute(endpoints, "api/dashboard");
        endpoints.MapControllers().RequireCors("CorsPolicy");
        // ...
    });
}

In the examples above, the policy allows cross-origin requests from https://example.com and no other origins. Change this URL to the URL where the client application is hosted.

Enable CORS with Attributes

You can add the EnableCORS attribute to a custom DashboardController to enable CORS only for this controller:

[EnableCors("CorsPolicy")]
public class CustomDashboardController : DashboardController {
    public CustomDashboardController(DashboardConfigurator conf) : base(conf) {
        // ...
    }
}

Enable CORS for ASP.NET Web Forms and MVC

For ASP.NET Web Forms and MVC, you can configure CORS in the Web.config file.

Simple way

To allow CORS requests from all origins, add the following custom headers:

<configuration>
    <system.webServer> 
        <httpProtocol> 
            <customHeaders> 
                <add name="Access-Control-Allow-Origin" value="*" />  
                <add name="Access-Control-Allow-Methods" value="GET, POST" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
            </customHeaders>
        </httpProtocol> 
    </system.webServer>
</configuration>

To allow any origin is insecure because any website can make cross-origin requests to the app.

Specify the client application's URL directly to prohibit any client from getting access to your server with personal info. Use the Access-Control-Allow-Origin response header to set it up:

<configuration>
    <system.webServer> 
        <httpProtocol> 
            <customHeaders> 
                <add name="Access-Control-Allow-Origin" value="https://example.com" />
                <add name="Access-Control-Allow-Methods" value="GET, POST" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
            </customHeaders>
        </httpProtocol> 
    </system.webServer>
</configuration>

In the example above, the policy allows cross-origin requests from https://example.com and no other origins. Change this URL to the URL where the client application is hosted.

You can add the EnableCORS attribute to a custom DashboardController to enable CORS policy only for this controller.

See Also