🐛(auth) allow several auth backend on m2m API

The previous `ServerToServerAuthentication` was raising authentication
failed error if anything is wrong (the header, the token) which prevents
any possibility to have several authentication backends.
This commit is contained in:
Quentin BEY 2025-05-13 23:31:28 +02:00
parent 30e7dd0344
commit 31d51be3e4
No known key found for this signature in database
GPG key ID: A9F8D7C7AFCB3F70
2 changed files with 16 additions and 4 deletions

View file

@ -689,7 +689,7 @@ class DocumentViewSet(
authentication_classes=[authentication.ServerToServerAuthentication],
detail=False,
methods=["post"],
permission_classes=[],
permission_classes=[permissions.IsAuthenticated],
url_path="create-for-owner",
)
@transaction.atomic

View file

@ -6,6 +6,15 @@ from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
class AuthenticatedServer:
"""
Simple class to represent an authenticated server to be used along the
IsAuthenticated permission.
"""
is_authenticated = True
class ServerToServerAuthentication(BaseAuthentication):
"""
Custom authentication class for server-to-server requests.
@ -39,13 +48,16 @@ class ServerToServerAuthentication(BaseAuthentication):
# Validate token format and existence
auth_parts = auth_header.split(" ")
if len(auth_parts) != 2 or auth_parts[0] != self.TOKEN_TYPE:
raise AuthenticationFailed("Invalid authorization header.")
# Do not raise here to leave the door open for other authentication methods
return None
token = auth_parts[1]
if token not in settings.SERVER_TO_SERVER_API_TOKENS:
raise AuthenticationFailed("Invalid server-to-server token.")
# Do not raise here to leave the door open for other authentication methods
return None
# Authentication is successful, but no user is authenticated
# Authentication is successful
return AuthenticatedServer(), token
def authenticate_header(self, request):
"""Return the WWW-Authenticate header value."""