From 193764c28bf1904be2c7ca4d55e0884f7936b92e Mon Sep 17 00:00:00 2001 From: Jeroen Dekkers Date: Thu, 31 Oct 2024 09:17:22 +0100 Subject: [PATCH] Fix auth token middleware with wrong format header (#3755) Co-authored-by: Jan Klopper --- rocky/rocky/middleware/auth_token.py | 7 ++++--- rocky/tests/test_api.py | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/rocky/rocky/middleware/auth_token.py b/rocky/rocky/middleware/auth_token.py index 3916bde4cd7..97907aa0bb4 100644 --- a/rocky/rocky/middleware/auth_token.py +++ b/rocky/rocky/middleware/auth_token.py @@ -9,12 +9,13 @@ def middleware(request): if not request.user.is_authenticated and "authorization" in request.headers: authenticator = TokenAuthentication() try: - user, token = authenticator.authenticate(request) + user_and_token = authenticator.authenticate(request) except APIException: return HttpResponseForbidden("Invalid token\n") else: - request.user = user - structlog.contextvars.bind_contextvars(auth_method="token") + if user_and_token: + request.user = user_and_token[0] + structlog.contextvars.bind_contextvars(auth_method="token") return get_response(request) diff --git a/rocky/tests/test_api.py b/rocky/tests/test_api.py index 5ff09ae06f0..536210ceb5e 100644 --- a/rocky/tests/test_api.py +++ b/rocky/tests/test_api.py @@ -11,3 +11,9 @@ def test_api_2fa_enabled(client, settings, admin_user): response = client.get("/api/v1/organization/", headers={"Authorization": f"Token {token}"}) assert response.status_code == 200 + + +# Regression test for https://github.com/minvws/nl-kat-coordination/issues/3754 +def test_auth_header_wrong_format(client, settings, admin_user): + response = client.get("/api/v1/organization/", headers={"Authorization": "Not a token"}) + assert response.status_code == 401