Authorized routes with CORs
See original GitHub issueFirst 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:
@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:
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:
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?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:16 (2 by maintainers)
Is there any update on this?
It seems more like a bug (or at least an oversight) than a feature request. I really want to use Chalice for its elegance and access to the AWS ecosystem, but I NEED the ability build endpoints that require authentication and allows CORS access.
@MichaelBoselowitz Thanks for your issue description. I’ve the same issue at the moment. Do you use your workaround without an extra lambda auth function?
@stealthycoin Does the feature request still exist and is it realistic that it will be processed?