Optional auth #709
-
Hi there, I was planning to change the response depending if the user is authenticated or not. How to achieve this? @api.get('',auth=AuthBearer()|None)
def optional_protected_route(request):
if request.auth:
return CustomResponse
else:
return GenericResponse By optional i meant user can include token or they can just do the request without token |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
I guess your authenticator class should return some Not-authenticated-user (like django does) class AuthBearer(HttpBearer):
def authenticate(self, request, token):
if token == "supersecret":
return AuthenticatedUser()
else:
return AnonymousUser()
...
@api.get('',auth=AuthBearer()|None)
def optional_protected_route(request):
if request.auth.is_anonymous:
return Custom
... |
Beta Was this translation helpful? Give feedback.
-
The solution is to override the def __call__(self, request: HttpRequest) -> Optional[Any]:
headers = get_headers(request)
auth_value = headers.get(self.header)
if not auth_value:
return AnonymousUser() # if there is no key, we return AnonymousUser object
parts = auth_value.split(" ")
if parts[0].lower() != self.openapi_scheme:
if settings.DEBUG:
logger.error(f"Unexpected auth - '{auth_value}'")
return None
token = " ".join(parts[1:])
return self.authenticate(request, token) Massive thanks to @eadwinCode for his help in eadwinCode/django-ninja-extra#60 (comment) |
Beta Was this translation helpful? Give feedback.
The solution is to override the
HttpBearer
class to returnAnonymousUser
Massive thanks to @eadwinCode for his help in eadwinCode/django…