|
| 1 | +""" |
| 2 | +Custom authenticators for the Support V1 API. |
| 3 | +""" |
| 4 | +import time |
| 5 | + |
| 6 | +import jwt |
| 7 | +from django.conf import settings |
| 8 | +from django.contrib.auth.models import AnonymousUser |
| 9 | +from jwt import ExpiredSignatureError, InvalidTokenError |
| 10 | +from rest_framework import authentication |
| 11 | +from rest_framework.authentication import get_authorization_header |
| 12 | + |
| 13 | + |
| 14 | +class JWTsignedOauthAppAuthentication(authentication.BaseAuthentication): |
| 15 | + """ |
| 16 | + Authentication class to verify JWTs signed by trusted services. |
| 17 | + Allows authentication for the OauthApplicationAPIView in Open edX. |
| 18 | + """ |
| 19 | + |
| 20 | + def authenticate(self, request): |
| 21 | + """ |
| 22 | + Extracts the JWT token from the Authorization header and verifies it. |
| 23 | + If authentication fails, it does NOT raise an exception to allow |
| 24 | + other authentication classes to attempt authentication. |
| 25 | + """ |
| 26 | + auth = get_authorization_header(request).split() |
| 27 | + |
| 28 | + if not auth or auth[0].lower() != b'bearer': |
| 29 | + return None |
| 30 | + |
| 31 | + if len(auth) != 2: |
| 32 | + return None |
| 33 | + |
| 34 | + token = auth[1] |
| 35 | + return self.authenticate_token(token) |
| 36 | + |
| 37 | + def authenticate_token(self, token): |
| 38 | + """ |
| 39 | + Attempts to authenticate the JWT token. If verification fails, |
| 40 | + returns None instead of raising an exception, allowing other authentication |
| 41 | + classes to handle authentication. |
| 42 | + """ |
| 43 | + try: |
| 44 | + decoded_payload = jwt.decode( |
| 45 | + token, |
| 46 | + settings.EOX_CORE_JWT_SIGNED_OAUTH_APP_PUBLIC_KEY, |
| 47 | + algorithms=["RS256"] |
| 48 | + ) |
| 49 | + |
| 50 | + if decoded_payload["exp"] < time.time(): |
| 51 | + return None |
| 52 | + |
| 53 | + return (AnonymousUser(), None) |
| 54 | + |
| 55 | + except (ExpiredSignatureError, InvalidTokenError): |
| 56 | + return None |
0 commit comments