Setting the BaseHandler's CORS origin header
Closed this issue · 0 comments
Another little change to our BaseHandler's headers to enable CORS (that is, secure cookie and origin based) communication between client and server. To make the server accept clients from any domain (origin), set the BaseHandler default headers to the following:
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", self.request.headers.get('Origin'))
self.set_header('Access-Control-Allow-Headers', 'origin, content-type, accept, authorization, x-total-count, content-range')
self.set_header("Access-Control-Allow-Credentials", 'true');
self.set_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
self.set_header('Content-Type', 'application/json')
Here, the relevant lines are:
self.set_header("Access-Control-Allow-Origin", self.request.headers.get('Origin'))
self.set_header("Access-Control-Allow-Credentials", 'true')
This sets the allowed domains that may access the server to the origin of the client that seeks to connect on a request by request basis. Which does bypass part of the security offered by CORS in the first place.
FYI: setting "Access-Control-Allow-Origin" to * doesn't work when you use credentials - and we need to allow credentials with our secure cookies.
We can also decide to set the allowed client domain(s) in our server's config file, and feed the allowed origin header an array of "approved origins". To get an idea how that would work, see the following function that defines such an array within the function itself:
def set_default_headers(self):
approved_origins = ['https://example.com:8080', 'https://example.info']
if self.request.headers['Origin'] in approved_origins:
self.set_header('Access-Control-Allow-Origin', self.request.headers['Origin'])
self.set_header('Access-Control-Allow-Headers', 'origin, content-type, accept, authorization, x-total-count, content-range')
self.set_header("Access-Control-Allow-Credentials", 'true');
self.set_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
self.set_header('Content-Type', 'application/json')
Maybe with a fallback to self.request.headers.get('Origin') if approved origins have not been set in the app's config.cfg.