| from rest_framework_simplejwt.authentication import JWTAuthentication |
| from rest_framework_simplejwt.exceptions import InvalidToken, AuthenticationFailed |
| from django.conf import settings |
| from rest_framework.authentication import CSRFCheck |
| from rest_framework import exceptions |
|
|
| def enforce_csrf(request): |
| """ |
| Enforce CSRF validation for cookie-based authentication. |
| """ |
| |
| def dummy_get_response(request): |
| return None |
| |
| check = CSRFCheck(dummy_get_response) |
| check.process_request(request) |
| reason = check.process_view(request, None, (), {}) |
| if reason: |
| raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) |
|
|
| class CookieJWTAuthentication(JWTAuthentication): |
| """ |
| Custom authentication class that checks for a JWT token in the cookies |
| if it's not provided in the Authorization header. |
| """ |
| def authenticate(self, request): |
| |
| header = self.get_header(request) |
| |
| if header is None: |
| |
| cookie_name = settings.SIMPLE_JWT.get('AUTH_COOKIE', 'access_token') |
| raw_token = request.COOKIES.get(cookie_name) |
| else: |
| raw_token = self.get_raw_token(header) |
| |
| if raw_token is None: |
| return None |
|
|
| try: |
| validated_token = self.get_validated_token(raw_token) |
| |
| |
| if header is None: |
| enforce_csrf(request) |
| |
| return self.get_user(validated_token), validated_token |
| except (InvalidToken, AuthenticationFailed): |
| return None |
|
|