Issue
Let's say I have the following Django Rest Framework authentication class order:
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
"MyCustomAuthClass",
],
...
}
Per the docs:
REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates.
Within my view I want to know which class authenticated successfully.
My use case is that I want to handle the third auth class differently for a specific endpoint. I'm currently re-authenticating which seems unnecessary and not performant:
def get(self, request):
if (
not TokenAuthentication().authenticate()
and not SessionAuthentication().authenticate()
and MyCustomAuthClass().authenticate(request)
):
# do this
else:
# do something else
Is there anyway to do that or is my approach the best option?
Solution
You can annotate the user returned by your authentication class like this:
class MyCustomAuthClass(BaseAuthentication):
def authenticate(self, request):
# get your user for example by token:
user = User.objects.get(token=request.META.get("HTTP_AUTHORIZATION"))
user.is_authenticated_on_my_custom_class = True
return (user, token)
Then in your view you can do:
if hasattr(request.user, "is_authenticated_on_my_custom_class") and request.user.is_authenticated_on_my_custom_class:
# do something for `MyCustomAuthClass`
Answered By - Brian Destura
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.