diff --git a/examples/service-fastapi/jupyterhub_config.py b/examples/service-fastapi/jupyterhub_config.py index 2b0e830b..9fb054ec 100644 --- a/examples/service-fastapi/jupyterhub_config.py +++ b/examples/service-fastapi/jupyterhub_config.py @@ -1,16 +1,31 @@ import os +import warnings -service = { - "name": "fastapi", - "url": "http://127.0.0.1:10202", - "command": ["uvicorn", "app:app", "--port", "10202"], -} -# If running behind a proxy, or in Docker / Kubernetes infrastructure, -# you probably need to set a different public Hub host than the -# internal JUPYTERHUB_API_URL host -if "PUBLIC_HOST" in os.environ: - public_host = os.environ["PUBLIC_HOST"] - service["oauth_redirect_uri"] = f"{public_host}/services/fastapi/oauth_callback" - service["environment"] = {"PUBLIC_HOST": public_host} +# When Swagger performs OAuth2 in the browser, it will set +# the request host + relative path as the redirect uri, causing a +# uri mismatch if the oauth_redirect_uri is just the relative path +# is set in the c.JupyterHub.services entry (as per default). +# Therefore need to know the request host ahead of time. +if "PUBLIC_HOST" not in os.environ: + msg = ( + "env PUBLIC_HOST is not set, defaulting to http://127.0.0.1:8000. " + "This can cause problems with OAuth. " + "Set PUBLIC_HOST to your public (browser accessible) host." + ) + warnings.warn(msg) + public_host = "http://127.0.0.1:8000" +else: + public_host = os.environ["PUBLIC_HOST"].rstrip('/') +service_name = "fastapi" +oauth_redirect_uri = f"{public_host}/services/{service_name}/oauth_callback" -c.JupyterHub.services = [service] +c.JupyterHub.services = [ + { + "name": service_name, + "url": "http://127.0.0.1:10202", + "command": ["uvicorn", "app:app", "--port", "10202"], + "admin": True, + "oauth_redirect_uri": oauth_redirect_uri, + "environment": {"PUBLIC_HOST": public_host}, + } +]