Skip to content

Commit 9acf6a8

Browse files
committed
allow token-authenticated requests cross-origin by default
we already apply this logic in our server-side checks, but browsers check `Access-Control-Allow-Origin` headers themselves as well, meaning that token-authenticated requests can’t be made cross-origin without CORS headers from browsers, only scripts. This makes default browser and server-side origin checks consistent
1 parent a8c6b8b commit 9acf6a8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

notebook/base/handlers.py

+26
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,16 @@ def set_default_headers(self):
281281
origin = self.get_origin()
282282
if origin and self.allow_origin_pat.match(origin):
283283
self.set_header("Access-Control-Allow-Origin", origin)
284+
elif (
285+
self.token_authenticated
286+
and "Access-Control-Allow-Origin" not in
287+
self.settings.get('headers', {})
288+
):
289+
# allow token-authenticated requests cross-origin by default.
290+
# only apply this exception if allow-origin has not been specified.
291+
self.set_header('Access-Control-Allow-Origin',
292+
self.request.headers.get('Origin', ''))
293+
284294
if self.allow_credentials:
285295
self.set_header("Access-Control-Allow-Credentials", 'true')
286296

@@ -517,6 +527,22 @@ def options(self, *args, **kwargs):
517527
self.set_header('Access-Control-Allow-Methods',
518528
'GET, PUT, POST, PATCH, DELETE, OPTIONS')
519529

530+
# if authorization header is requested,
531+
# that means the request is token-authenticated.
532+
# avoid browser-side rejection of the preflight request.
533+
# only allow this exception if allow_origin has not been specified.
534+
requested_headers = self.request.headers.get('Access-Control-Request-Headers', '').split(',')
535+
if requested_headers and any(
536+
h.strip().lower() == 'authorization'
537+
for h in requested_headers
538+
) and (
539+
self.allow_origin
540+
or self.allow_origin_pat
541+
or 'Access-Control-Allow-Origin' in self.settings.get('headers', {})
542+
):
543+
self.set_header('Access-Control-Allow-Origin',
544+
self.request.headers.get('Origin', ''))
545+
520546

521547
class Template404(IPythonHandler):
522548
"""Render our 404 template"""

0 commit comments

Comments
 (0)