|
| 1 | +from django.apps import apps as django_apps |
| 2 | +from django.conf import settings |
| 3 | +from django.utils.encoding import force_str |
| 4 | +from django.utils.module_loading import import_string |
| 5 | +from django.utils.translation import gettext as _ |
| 6 | +from rest_framework import HTTP_HEADER_ENCODING, exceptions |
| 7 | +from rest_framework.authentication import BaseAuthentication |
| 8 | + |
| 9 | +from .validator import TokenError, TokenValidator |
| 10 | + |
| 11 | +# 2 objects expected when parsing Auth Header: 'Bearer' + token |
| 12 | +VALID_AUTH_HEADER_LENGTH = 2 |
| 13 | + |
| 14 | + |
| 15 | +def get_authorization_header(request): |
| 16 | + """ |
| 17 | + Return request's 'X-UHD-AUTH:' header, as a bytestring. |
| 18 | +
|
| 19 | + Hide some test client ickyness where the header can be unicode. |
| 20 | + """ |
| 21 | + auth = request.META.get("HTTP_X_UHD_AUTH", b"") |
| 22 | + if isinstance(auth, str): |
| 23 | + # Work around django test client oddness |
| 24 | + auth = auth.encode(HTTP_HEADER_ENCODING) |
| 25 | + return auth |
| 26 | + |
| 27 | + |
| 28 | +class JSONWebTokenAuthentication(BaseAuthentication): |
| 29 | + """Token based authentication using the JSON Web Token standard. |
| 30 | + Based on https://github.com/labd/django-cognito-jwt and modified |
| 31 | + to suit our use case |
| 32 | + """ |
| 33 | + |
| 34 | + def authenticate(self, request): |
| 35 | + """Entrypoint for Django Rest Framework""" |
| 36 | + jwt_token = self.get_jwt_token(request) |
| 37 | + if jwt_token is None: |
| 38 | + return None |
| 39 | + |
| 40 | + # Authenticate token |
| 41 | + try: |
| 42 | + token_validator = self.get_token_validator(request) |
| 43 | + jwt_payload = token_validator.validate(jwt_token) |
| 44 | + except TokenError: |
| 45 | + raise exceptions.AuthenticationFailed from None |
| 46 | + |
| 47 | + custom_user_manager = self.get_custom_user_manager() |
| 48 | + if custom_user_manager: |
| 49 | + user = custom_user_manager.get_or_create_for_cognito(jwt_payload) |
| 50 | + else: |
| 51 | + user_model = self.get_user_model() |
| 52 | + user = user_model.objects.get_or_create_for_cognito(jwt_payload) |
| 53 | + return (user, jwt_token) |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def get_custom_user_manager(): |
| 57 | + """If COGNITO_USER_MANAGER is set, then the user object is obtained |
| 58 | + via get_or_create_for_cognito on the user manager, this allows use |
| 59 | + of the default unmodified Django User model""" |
| 60 | + result = None |
| 61 | + custom_user_manager_path = getattr(settings, "COGNITO_USER_MANAGER", False) |
| 62 | + if custom_user_manager_path: |
| 63 | + result = import_string(custom_user_manager_path)() |
| 64 | + return result |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + def get_user_model(): |
| 68 | + user_model = getattr(settings, "COGNITO_USER_MODEL", settings.AUTH_USER_MODEL) |
| 69 | + return django_apps.get_model(user_model, require_ready=False) |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def get_jwt_token(request): |
| 73 | + auth = get_authorization_header(request).split() |
| 74 | + if not auth or force_str(auth[0].lower()) != "bearer": |
| 75 | + return None |
| 76 | + |
| 77 | + if len(auth) == 1: |
| 78 | + msg = _("Invalid Authorization header. No credentials provided.") |
| 79 | + raise exceptions.AuthenticationFailed(msg) |
| 80 | + if len(auth) > VALID_AUTH_HEADER_LENGTH: |
| 81 | + msg = _( |
| 82 | + "Invalid Authorization header. Credentials string " |
| 83 | + "should not contain spaces." |
| 84 | + ) |
| 85 | + raise exceptions.AuthenticationFailed(msg) |
| 86 | + |
| 87 | + return auth[1] |
| 88 | + |
| 89 | + @staticmethod |
| 90 | + def get_token_validator(request): |
| 91 | + return TokenValidator( |
| 92 | + settings.COGNITO_AWS_REGION, |
| 93 | + settings.COGNITO_USER_POOL, |
| 94 | + settings.COGNITO_AUDIENCE, |
| 95 | + ) |
| 96 | + |
| 97 | + @staticmethod |
| 98 | + def authenticate_header(request): |
| 99 | + """ |
| 100 | + Method required by the DRF in order to return 401 responses for authentication failures, instead of 403. |
| 101 | + More details in https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication. |
| 102 | + """ |
| 103 | + return "Bearer: api" |
0 commit comments