-
Notifications
You must be signed in to change notification settings - Fork 218
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: return 401 when authorization is invalid when including header b…
…y implementing middleware wrapper
- Loading branch information
Showing
3 changed files
with
23 additions
and
26 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from django.http import JsonResponse | ||
from rest_framework.status import HTTP_401_UNAUTHORIZED | ||
|
||
def strict_auth_middleware(get_response): | ||
# Inner function to process each request | ||
def middleware(request): | ||
# Extract the Authorization header from the request | ||
auth_header = request.headers.get('Authorization', None) | ||
|
||
# If the Authorization header is present | ||
if auth_header: | ||
# Check if the user is anonymous or authentication failed | ||
if request.user.is_anonymous or request.auth is None: | ||
# Return a 401 Unauthorized response | ||
return JsonResponse({'detail': 'Invalid token.'}, status=HTTP_401_UNAUTHORIZED) | ||
|
||
# If no Authorization header is present or authentication is successful, | ||
# continue processing the request as normal | ||
return get_response(request) | ||
|
||
return middleware |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters