From e695ac86e3dde75f79ff7484cc20719c4bf0d174 Mon Sep 17 00:00:00 2001 From: Adrien Kunysz Date: Wed, 20 Nov 2024 09:06:03 +0100 Subject: [PATCH] PB-1009: trust API Gateway to authenticate users. We are delegating the authentication to API Gateway which sets the `Geoadmin-Username` header. However due to how API Gateway and JWT-based authentication work, the header is only set at login time. It is on the service to keep track of the user afterwards. This change updates service-stac in Dev to trust the `Geoadmin-Username` header if it is present. Then service-stac persists the user across their whole session. Relevant documentation is at https://docs.djangoproject.com/en/5.1/howto/auth-remote-user/ --- app/config/settings_dev.py | 20 ++++++++++++++++++++ app/middleware/apigw.py | 4 ++++ 2 files changed, 24 insertions(+) create mode 100644 app/middleware/apigw.py diff --git a/app/config/settings_dev.py b/app/config/settings_dev.py index 3e606239..ce71bd72 100644 --- a/app/config/settings_dev.py +++ b/app/config/settings_dev.py @@ -65,3 +65,23 @@ AWS_SETTINGS['managed']['access_type'] = "key" AWS_SETTINGS['managed']['ACCESS_KEY_ID'] = env("LEGACY_AWS_ACCESS_KEY_ID") AWS_SETTINGS['managed']['SECRET_ACCESS_KEY'] = env("LEGACY_AWS_SECRET_ACCESS_KEY") + +# API Gateway integration PB-1009 +AUTHENTICATION_BACKENDS = [ + "django.contrib.auth.backends.RemoteUserBackend", + # We keep ModelBackend as fallback until we have moved all users to Cognito. + "django.contrib.auth.backends.ModelBackend", +] +MIDDLEWARE += [ + "django.contrib.auth.middleware.AuthenticationMiddleware", + "middleware.apigw.ApiGatewayMiddleware", +] +# By default sessions expire after two weeks. +# Sessions are only useful for user tracking in the admin UI. For security +# reason we should expire these sessions as soon as possible. Given the use +# case, it seems reasonable to log out users after 8h of inactivity or whenever +# they restart their browser. +SESSION_COOKIE_AGE = 60 * 60 * 8 +SESSION_EXPIRE_AT_BROWSER_CLOSE = True +SESSION_COOKIE_SAMESITE = "Strict" +SESSION_COOKIE_SECURE = True diff --git a/app/middleware/apigw.py b/app/middleware/apigw.py new file mode 100644 index 00000000..f5d68c40 --- /dev/null +++ b/app/middleware/apigw.py @@ -0,0 +1,4 @@ +from django.contrib.auth.middleware import PersistentRemoteUserMiddleware + +class ApiGatewayMiddleware(PersistentRemoteUserMiddleware): + header = "HTTP_GEOADMIN_USERNAME"