Skip to content

Commit

Permalink
fix: return 401 when authorization is invalid when including header b…
Browse files Browse the repository at this point in the history
…y implementing middleware wrapper
  • Loading branch information
carlosm22700 committed Feb 18, 2024
2 parents 48b9c92 + 8c2a9f7 commit fd01898
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 26 deletions.
25 changes: 0 additions & 25 deletions api/api/middleware/response_headers_middleware.py

This file was deleted.

21 changes: 21 additions & 0 deletions api/api/middleware/strict_auth_middleware.py
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
3 changes: 2 additions & 1 deletion api/conf/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"api.middleware.response_headers_middleware.response_headers_middleware",
"oauth2_provider.middleware.OAuth2TokenMiddleware",
"api.middleware.strict_auth_middleware.strict_auth_middleware",
]

# Storage
Expand Down

0 comments on commit fd01898

Please sign in to comment.