Overview
Cross-Origin Resource Sharing (CORS) configuration in Silky is handled by the Silky.Http.CorsAccessor package. It provides a flexible, configuration-driven CORS policy that works seamlessly with the gateway.
Installation
<PackageReference Include="Silky.Http.CorsAccessor" Version="3.9.2" />
Setup
Module
[DependsOn(
typeof(CorsAccessorModule),
typeof(GatewayHostModule)
)]
public class GatewayModule : SilkyModule { }
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSilkyHttpCore()
.AddCorsAccessor(); // reads config from CorsAccessor section
}
public void Configure(IApplicationBuilder app)
{
app.UseCorsAccessor(); // must come before authentication and routing
app.UseAuthentication();
app.UseAuthorization();
app.UseSilkyRpcProxy();
}
Configuration
Configure CORS policies in appsettings.json under the CorsAccessor key:
{
"CorsAccessor": {
"PolicyName": "CorsPolicy",
"WithOrigins": [
"http://localhost:3000",
"https://app.example.com"
],
"WithHeaders": [
"Authorization",
"Content-Type",
"X-Requested-With"
],
"WithMethods": [
"GET", "POST", "PUT", "DELETE", "OPTIONS"
],
"AllowCredentials": true,
"SetPreflightMaxAge": 3600
}
}
Allow All Origins (Development Only)
{
"CorsAccessor": {
"WithOrigins": [ "*" ],
"AllowCredentials": false
}
}
Warning
Setting WithOrigins: ["*"] with AllowCredentials: true is not allowed by browsers. Use explicit origins when credentials are required.
Configuration Reference
| Property | Type | Default | Description |
|---|---|---|---|
PolicyName | string | "CorsPolicy" | Named policy identifier |
WithOrigins | string[] | [] | Allowed origins; use ["*"] for any |
WithHeaders | string[] | [] | Allowed request headers |
WithMethods | string[] | [] | Allowed HTTP methods |
AllowCredentials | bool | false | Allow cookies and auth headers cross-origin |
SetPreflightMaxAge | int | 0 | Max age (seconds) for preflight cache |
WithExposedHeaders | string[] | [] | Response headers exposed to the browser |
Per-Service Entry Override
For fine-grained control, use the [AllowCors] attribute on individual service entries:
[ServiceRoute]
public interface IPublicApiService
{
[HttpGet("public/data")]
[AllowCors("*")]
Task<PublicDataOutput> GetPublicDataAsync();
}
