Skip to content

Allow for configuration of allow_origin_regex for CORS settings #297

@batpad

Description

@batpad

Currently, we can configure different CORS options as environment variables here: https://github.com/stac-utils/stac-fastapi-pgstac/blob/main/stac_fastapi/pgstac/config.py#L180

This list of configurable options currently does not include allow_origin_regex.

Why one would need this

In my situation, I am running stac-fastapi-pgstac behind stac-auth-proxy which handles authentication. Since this means I need to send an Authorization header from the frontend, I need to set allow_credentials to True. If allow_credentials is set to True, browsers will not accept a value of * for allow_origins: *.

Therefore, currently, to be able to whitelist frontend domains that are allowed to make CORS requests to the API, I need to whitelist each one and add them explicitly to a comma separated list in allow_origins. As a simple example, if I whitelist http://localhost:3000 to be able to test locally, I can't run my frontend on say http://localhost:3001, and I would need a backend change to add http://localhost:3001 to allow_origins for it to work. This also means that anyone wanting to make a frontend talking to my API needs me to add their URL to allow_origins for their site to work. This is sometimes desirable, and sometimes not.

FastAPI provides the allow_origin_regex option to deal with this: one can then specify allowed_origins as a regular expression: so one could do something like "http://localhost*" to allow localhost on any port, or just ".*" to allow any origin - the way FastAPI treats the allow_origins_regex option is that if the Origin matches the regex, it will "reflect" the incoming Origin in the Access-Control-Allow-Origin header, so that you can use allow_credentials as True, and still be more liberal in what frontend domains are allowed to make CORS requests.

Change Requested

I think the only thing needed here would be to add allow_origin_regex to the settings and the options passed to the CORS middleware so that it is configurable. We would just need to figure out what the default value should be to not break backwards compatibility.

cc @hrodmn @alukach

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions