resgateio / resgate

A Realtime API Gateway used with NATS to build REST, real time, and RPC APIs, where all your clients are synchronized seamlessly.
https://resgate.io
MIT License
689 stars 67 forks source link

CORS Support #141

Closed jirenius closed 4 years ago

jirenius commented 4 years ago

Issue

Resgate should have a configuration to enable CORS support for the REST API.

Solution

Alternative 1: Simple CORS setting

A boolean flag --cors would enable the adding of the HTTP header to the REST API:

Access-Control-Allow-Origin: *

This would cover the most common use case.

Alternative 2: Allow Origin setting

A string flag --alloworigin https://resgate.io would enable the adding of the HTTP header, but with a custom origin:

Access-Control-Allow-Origin: https://resgate.io

This would allow for a more flexible configuration.

Alternative 3: Header setting

A repeatable string flag that allows custom headers to be added to the response:

--header "Access-Control-Allow-Origin: *" --header "Custom-Header: foo"

This would allow full flexibility, while making it less obvious how to add CORS support.

Note: Added headers should be applied for both WS and HTTP, while the Access-Control-Allow-Origin header may be skipped on WS responses.

psiservices-dharrison commented 4 years ago

Option#3 seems the most flexible. My second choice would be Option#2. For an edge case, would there be a way to support multiple domains in the origin/CORS allow header, without just using the wildcard *?

jirenius commented 4 years ago

@psiservices-dharrison Good question.
The header spec only allows a single domain in a response. By using Option#2, with the addition of allowing multiple flags (or possibly a single semi-colon separated string):

-alloworigin https://resgate.io -alloworigin https://example.com

Resgate could verify that the Origin header matches one of Resgate's allowed origins, and returning that origin in the Access-Control-Allow-Origin header, including Vary: Origin.

See: https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains

I think I prefer that option.
Option#3 might sound good, but in reality you seldom want to add a static header. Better to make specific (and dynamic) solutions to specific needs... like Option#2.

jirenius commented 4 years ago

Resolved in #149