aws / aws/chalice

Authorized routes with CORs

Open
#1,290 18 comments 6 reactions 0 assignees View on GitHub
feature-request
Dominant language
Python
Stars
11.1k
Forks
1k
Avg merge
1d 22h
Merged PRs (30d)
2

Description

First off, thank you for creating and maintaining this library! It has been a real joy to use.

The issue I'm having is there doesn't seem to be an easy way to create an unauthenticated CORs preflight route for an authenticated route, e.g. if you create a route with the following:
```python
@app.route('/', authorizer=authorizer, cors=True)
def index():
pass
```

You end up having an authenticated CORs preflight route—this doesn't seem like very good practice, or at least it's not very ergonomic when writing a frontend to talk to this API.

The only work around I've found to support unauthenticated preflight `OPTIONS` routes on authenticated routes is to create my own `OPTIONS` routes and respond to the preflight requests manually.

To make this a little more bearable, I created a utility function to automate this process a bit:
```python
def create_cors_routes(app, route, methods=['GET']):
def cors_route(*args, **kwargs):
request = app.current_request
headers = {
'Access-Control-Allow-Method': ','.join(methods),
'Access-Control-Allow-Origin': ','.join(ALLOWED_ORIGINS),
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
}
origin = request.headers.get('origin', '')
if origin in ALLOWED_ORIGINS:
headers.update({ 'Access-Control-Allow-Origin': origin })
return Response(
body=None,
headers=headers
)
app.route(route, methods=['OPTIONS'])(cors_route)
```

Once the utility function is in place, it can be used like the following:
```python
create_cors_routes(app, '/resource', methods=['GET', 'POST'])
create_cors_routes(
app,
'/resource/{id}',
methods=['GET', 'PUT', 'PATCH', 'DELETE']
)
```

Is there a better way to do this / can the `CORSConfig` be extended to allow for unauthenticated preflight routes?

Contributor guide

Open the contributing guide

Research direction

Start by reading the CORSConfig behavior and the app.route handling for routes with authorizers and cors enabled. Trace how OPTIONS requests are generated and authenticated, then define and verify a configuration path that permits unauthenticated preflight responses while keeping the target route protected.

Written by the indexing model from the issue text.

Assessment

Tech stack
aws, python
Domain
api, backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.