Cross Origin Resource Sharing (CORS) is an additional security check performed by modern browsers to prevent unauthorized requests between different domains.
By default, Falcon’s built-in CORS support is disabled, so that any cross-origin
requests will be blocked by the browser. Passing
cause the framework to include the necessary response headers to allow access
from any origin to any route in the app. Individual responders may override this
behavior by setting the
Access-Control-Allow-Origin header explicitly.
Whether or not you implement a CORS policy, we recommend also putting a robust AuthN/Z layer in place to authorize individual clients, as needed, to protect sensitive resources.
Directly passing the
falcon.CORSMiddleware middleware to the application
allows customization of the CORS policy applied. The middleware allows customizing
the allowed origins, if credentials should be allowed and if additional headers
can be exposed.
import falcon # Enable a simple CORS policy for all responses app = falcon.App(cors_enable=True) # Alternatively, enable CORS policy for example.com and allow # credentials app = falcon.App(middleware=falcon.CORSMiddleware( allow_origins='example.com', allow_credentials='*'))
import falcon.asgi # Enable a simple CORS policy for all responses app = falcon.asgi.App(cors_enable=True) # Alternatively, Enable CORS policy for example.com and allow # credentials app = falcon.asgi.App(middleware=falcon.CORSMiddleware( allow_origins='example.com', allow_credentials='*'))
cors_enable parameter set to
True should be seen as
mutually exclusive with directly passing an instance of
CORSMiddleware to the application’s initializer.
- class falcon.CORSMiddleware(allow_origins: Union[str, Iterable[str]] = '*', expose_headers: Optional[Union[str, Iterable[str]]] = None, allow_credentials: Optional[Union[str, Iterable[str]]] = None)¶
This middleware provides a simple out-of-the box CORS policy, including handling of preflighted requests from the browser.
- Keyword Arguments
List of additional response headers to expose via the
Access-Control-Expose-Headersheader. These headers are in addition to the CORS-safelisted ones:
allow_credentials (Optional[Union[str, Iterable[str]]]) – List of origins (case sensitive) for which to allow credentials via the
Access-Control-Allow-Credentialsheader. The string
'*'acts as a wildcard, matching every allowed origin, while
Nonedisallows all origins. This parameter takes effect only if the origin is allowed by the