Simplifying CORS at API Gateway and for .NET APIs and Node.js

Vineet Sharma
4 min readJan 16, 2025

Simplifying and managing CORS (Cross-Origin Resource Sharing) in a cloud environment with gateways like Azure API Management, Ocelot, or AWS API Gateway, .NET APIs and Node.js requires understanding how CORS works and tailoring solutions for each gateway. Below is an elaborated guide to streamline CORS management across these platforms:

1. General Overview of CORS

CORS is a browser-enforced security feature that allows or restricts cross-origin requests. Managing CORS centrally at the API Gateway reduces complexity in downstream services.

2. Azure API Management

Azure API Management allows CORS to be configured at the gateway level to handle all requests centrally.

Steps to Configure CORS in Azure API Management:

  1. Navigate to API in Azure Portal:
  • Go to API Management > APIs.
  • Select the API where you want to enable CORS.
  1. Add CORS Policy:
  • Under Design > Inbound Processing, add the CORS policy.
  • Example:
<inbound>
{" "}
<base />{" "}
<cors>
{"
"}
<allowed-origins>
{"
"}
<origin>https://example.com</origin>{"
"}
</allowed-origins>{"
"}
<allowed-methods>
{"
"}
<method>GET</method> <method>POST</method> <method>PUT</method>{"
"}
</allowed-methods>{"
"}
<allowed-headers>
{"
"}
<header>Authorization</header> <header>Content-Type</header>{"
"}
</allowed-headers>{"
"}
<allow-credentials>true</allow-credentials>{"
"}
</cors>{"
"}
</inbound>;
  1. Deploy and Test:
  • Save and deploy the API.
  • Test using browser dev tools or API tools like Postman.

3. Ocelot Gateway (for .NET Microservices)

Ocelot is a lightweight API Gateway for microservices in .NET.

Steps to Enable CORS in Ocelot:

  1. Add Middleware for CORS: In Program.cs:
var builder = WebApplication.CreateBuilder(args);

// Add CORS services
builder.Services.AddCors(options =>
{
options.AddPolicy("OcelotPolicy", policy =>
{
policy.WithOrigins("https://example.com") // Replace with your allowed origin
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});

// Add Ocelot services
builder.Services.AddOcelot();

var app = builder.Build();

// Use CORS middleware
app.UseCors("OcelotPolicy");

// Use Ocelot middleware
app.UseOcelot().Wait();

app.Run();

2. Configure Routes in ocelot.json:

{
"Routes": [
{
"DownstreamPathTemplate": "/api/{everything}",
"UpstreamPathTemplate": "/api/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5000
}
]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://gateway.example.com"
}
}

4. AWS API Gateway

AWS API Gateway simplifies CORS with built-in settings for REST and HTTP APIs.

Steps for REST APIs:

  1. Enable CORS:
  • Go to AWS Console > API Gateway > APIs.
  • Select a resource (e.g., /items) and enable CORS via the Actions menu.

2. Customize Headers:

  • Define allowed origins, methods, headers, and credentials.
  • Add OPTIONS for preflight requests.
  1. Deploy the API.

Steps for HTTP APIs:

  1. Enable CORS Globally:
  • In the API’s CORS settings, specify allowed origins, methods, headers, and credentials.
  • Example YAML for AWS SAM:
MyHttpApi:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: MyHttpApi
ProtocolType: HTTP
CorsConfiguration:
AllowOrigins:
- "https://example.com"
AllowMethods:
- GET
- POST
AllowHeaders:
- Authorization
- Content-Type
AllowCredentials: true

5. Backend Services

If CORS is not managed at the gateway level, enable it in your backend services.

Example for .NET API:

  1. Add CORS middleware in Program.cs:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
{
policy.WithOrigins("https://example.com") // Replace with your allowed origin
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});

var app = builder.Build();

app.UseCors("AllowSpecificOrigin");
app.MapControllers();

app.Run();

Example for Node.js API:

  1. Install and use the cors middleware:
npm install cors

2. Enable CORS in your application:

const express = require('express');
const cors = require('cors');
const app = express();

const corsOptions = {
origin: 'https://example.com', // Replace with your allowed origin
methods: 'GET,POST,PUT,DELETE',
allowedHeaders: 'Authorization,Content-Type',
credentials: true, // Allow cookies or authentication
};

app.use(cors(corsOptions));

app.get('/', (req, res) => {
res.json({ message: 'CORS is configured!' });
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

6. Key Recommendations

  1. Centralize CORS in Gateways:
  • Handle CORS in API Gateways (Azure API Management, Ocelot, or AWS) when possible.
  • Reduces complexity in backend services.

2. Restrict Origins:

  • Avoid using * in production. List trusted origins explicitly.

3. Optimize Preflight Requests:

  • Cache preflight OPTIONS responses for performance optimization.

4. Test Thoroughly:

  • Use browser tools or Postman to validate CORS headers and behavior.

7. Conclusion

Managing Cross-Origin Resource Sharing (CORS) effectively is crucial for modern API architectures. By centralizing CORS configuration at the API Gateway level, you can streamline cross-origin requests while maintaining consistent security across backend services.

Cloud API Gateways like Azure API Management, AWS API Gateway, and Ocelot (for .NET) provide robust tools to handle CORS centrally. These platforms allow you to specify allowed origins, methods, headers, and credentials. For example, Azure API Management uses XML-based policies, AWS API Gateway supports built-in CORS settings, and Ocelot integrates seamlessly with .NET CORS middleware.

If CORS is not managed at the gateway level, it can be configured in backend services:

Sign up to discover human stories that deepen your understanding of the world.

No responses yet

Write a response

Recommended from Medium

Lists