Search code examples
reactjsdjangodockerauthenticationtoken

Django Authorization Token returns AnonymousUser


I'm trying to get the user from a request. My reactjs/postman client sends the token in the header as follow:

'Authorization' : 'Token token_string'

For some reason, when I using self.request.user in the view (GET request) I'm getting AnonymousUser.

The token is valid, using the following code I'm getting the correct user, not AnonymousUser:

from rest_framework.authtoken.models import Token
from django.shortcuts import get_object_or_404

user = get_object_or_404(Token, pk=token_string).user

Here is my setting.py MIDDLEWARE:

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

Here is my User model:

class User(django.contrib.auth.models.User):
  avatar = models.URLField(max_length=255, blank=True)
  date = models.DateTimeField(auto_now_add=True)  
  name =  models.CharField(max_length=256)

Note: when I'm calling the request using the browser after logging in to Django admin I'm getting the user properly.


Solution

  • Django assigns 'AnonymousUser' to request.user whenever the user isn't logged in, if you logged into you Django admin, you're logged in to the site. So that would be why you're getting the correct user in that instance.