Reputation: 1432
I am using JWT authentication for my django-rest-framework and react project. So, I have defined a URL path that provides the JWT token.
path('api/auth/token/', obtain_jwt_token),
I have defined another path which retrieves the current logged-in user:
path('current_user/', current_user, name='current-user'),
current_user:
@api_view(['GET'])
def current_user(request):
if not request.user.is_authenticated:
return Response('User is not authenticated')
profile = Profile.objects.get(user=request.user)
serializer = CurrentProfileSerializer(profile)
return Response(serializer.data)
The problem is, after I log in at api/auth/token/
and then go to current_user/
, I am getting 'User is not authenticated' response. I thought that obtain_jwt_token
returns a token and logs in the user to request.user
. Am I wrong for assuming this? Please ask if I need to provide any more details.
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
Upvotes: 0
Views: 170
Reputation: 2591
when you receive token in api/auth/token reuqest, you should store it in frontend. then in currect_user request, use this stored token in header of request. like this:
Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImFsaUBtYWlsLmNvbSIsImV4cCI6MTUzMzcxNjUzNCwiZW1haWwiOiJhbGlAbWFpbC5jb20ifQWfVfp6Nfj9gvedTkqhqlwZhAwzi2YK64cx2FpRLms
Upvotes: 1