DRF and Knox showing logged in user as anonymous (Django)

581 views Asked by At

I created an API with DRF and Knox and, I am using token based authentication. Everything is working except the system is showing the logged in user as anonymous.

I tried all this:

            current_user = request.user
            print(current_user.is_anonymous) # True
            print(current_user.is_authenticated) # False
            print(current_user.is_staff) # False
            print(current_user.is_superuser) # false
            print(current_user.is_active) # false

            u = User()
            print(u.id) # None

I need the user id of the logged in user because I am using that as a foreign key in the other table. I checked the auth_user table and it has all the columns. Is there any way to get the user id or convert the anonymous user to authenticated user ?

Thanks AJ

1

There are 1 answers

1
Memet Aktan On
from knox.auth import TokenAuthentication
token = request.META.get('HTTP_AUTHORIZATION', False)
if token:
    token = str(token).split()[1].encode("utf-8")
    knoxAuth = TokenAuthentication()
    user, auth_token = knoxAuth.authenticate_credentials(token)
    request.user = user