Optional auth #709
Answered
by
baseplate-admin
baseplate-admin
asked this question in
Q&A
-
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.
Answered by
baseplate-admin
Apr 2, 2023
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.
5 replies
-
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.
0 replies
Answer selected by
baseplate-admin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The solution is to override the
HttpBearer
class to returnAnonymousUser
Massive thanks to @eadwinCode for his help in eadwinCode/django…