Sobes.tech
Junior — Middle

Can you explain what CORS is and why it is needed in web development?

sobes.tech AI

Answer from AI

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that allows controlling which external domains can access your web server's resources.

By default, browsers block requests from one domain to another (cross-origin requests) due to the Same-Origin Policy. CORS allows the server to explicitly permit or deny such requests.

How it works:

  • The client (browser) sends a request with an Origin header indicating the source domain.
  • The server checks this domain and, if allowed, responds with an Access-Control-Allow-Origin header specifying the permitted domain or * for all.
  • If the header is absent or the domain is not allowed, the browser blocks access to the response.

Example of CORS configuration in ASP.NET Core:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.WithOrigins("https://example.com")
                              .AllowAnyHeader()
                              .AllowAnyMethod());
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowSpecificOrigin");
    // other middleware
}

Thus, CORS helps securely manage access to APIs or resources from different domains.

Can you explain what CORS is and why it is needed in… - sobes.tech