1

I am trying to use JWT token authentication with Django rest framework. I was able to successfully get the access and refresh token. And I made sure that the token is valid. But when I try to access some protected apiview with the access token. It says

{"detail":"Authentication credentials were not provided."}.

curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/

However, on server side I did get the request.META with a HTTP_AUTHORIZAITON field that contains the above token.

I'm currently developing on localhost instead of Apache, with following files and configurations:

In views.py:

class GetMyInfo(views.APIView):

 def get(self,request):
  print(request.META)
  user = request.user
  profile = user.profile
  profile_serializer = ProfileSerializer(instance = profile)
  return Response(profile_serializer.data, status = HTTP_200_OK)

In url.py:

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^api/$', get_schema_view()),
    re_path(r'^api/auth/', include('rest_framework.urls')),
    re_path(r'^api/auth/token/obtain/$', TokenObtainPairView.as_view(), name = 'token_obtain_pair'),
    re_path(r'^api/auth/token/refresh/$', TokenRefreshView.as_view(), name = 'token_refresh'),
    re_path(r'^api/auth/token/verify/$', TokenVerifyView.as_view(), name = 'token_verify'),
    #re_path(r'^api-token-auth/', authviews.obtain_auth_token, name = 'obtain_auth_token'),
    re_path(r'^users/$', views.CreateUser.as_view(), name = 'register'),
    re_path(r'users/(?P<uuid>[0-9a-f-]+)/$', views.GetUserInfo.as_view(), name = 'info'),
    re_path(r'users/me/$', views.GetMyInfo.as_view(), name = 'myinfo'),
]

settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api'
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES':(
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES':(
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        #'rest_framework.authentication.SessionAuthentication',
        #'rest_framework.authentication.TokenAuthentication',
        #'rest_framework.authentication.BasicAuthentication',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}


AUTH_USER_MODEL = 'api.User'

In models.py:

@receiver(post_save, sender = settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance = None, created = False, **kwargs):
 if created:
  Token.objects.create(user = instance)

class User(AbstractUser):
 uuid = models.UUIDField(default = uuid.uuid4, unique = True)

class Profile(models.Model):
 owner = models.OneToOneField(settings.AUTH_USER_MODEL, 
 on_delete = models.CASCADE, 
 primary_key = True,
 related_name = 'profile')
 displayname = models.CharField(max_length = 30)
 location = models.CharField(max_length = 100, null = True)
 bio = models.CharField(max_length = 500, null = True)
 relationships = models.ManyToManyField('self', 
 through = 'Followings', 
 symmetrical = False,
 related_name = 'related_to')

1 Answer 1

3

From what I see you are using rest_framework_simplejwt package to handle JWT authentication.

A sample from the docs specify you should use: Authorization: Bearer <token> to access protected views.

So instead of

curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/

use:

curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to use JWT, you should specify it in the configuration: SIMPLE_JWT = {'AUTH_HEADER_TYPES': ['JWT']}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.