CORS question?
Closed this issue · 1 comments
Hello,
I'm facing a problem with SSE library related to CORS issue.
The portal is on a domain: https://portal.example.com
The API is on a domain: https://api.example.com
The portal is able to call all controllers with the default mapping: api/[controller]
The CORS is working for all endpoints and for now I'm using least secure setting like this one:
services.AddCors(options => { options.AddDefaultPolicy(builder => builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod().Build()); });
Except for SSE code in the front end:
const source = new EventSource("https://api.example.com/updates");
And the configured endpoint for the SSE:
app.MapServerSentEvents("/updates");
I'm able to test it with CURL successfully:
curl -N --http2 -H "Accept:text/event-stream" https://api.example.com/updates
Noticed that when loading the portal and activating the event listening, it's always pending, until the first event is sent I get the CORS issue.
Am I missing something in the configuation for the CORS and SSE?
Thanks
Hi @kayanbuild,
As long as you have added the CORS middleware to the pipeline (by calling UseCors
), everything should work. You can either just register the middleware with a specific policy or register middleware with default policy and provide policy per-endpoint (with RequireCors
).
For example:
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().Build();
});
});
...
}
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
...
app .UseRouting()
.UseCors()
.UseEndpoints(endpoints =>
{
endpoints.MapServerSentEvents("/updates");
...
});
}
or (what is probably closer to what you are using):
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().Build();
});
});
...
}
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
...
app.UseCors();
app.MapServerSentEvents("/updates");
...
}
}
You can read more about options for configuring CORS middleware here.