I am using jwt authentication on my Django app. When user login to my website my server sends jwt token and refresh token to the browser cookie but I am getting "User is not authenticated."
error and not getting any profile data for my user_profile/
api endpoint.
Even I can see jwt token and refresh token also avaiable on the browser cookie after user login and aslo {withCredentials:true}
in my axois post.
here is my login code:
@api_view(['POST'])
def user_login(request):
if request.method == 'POST':
...others code
refresh = RefreshToken.for_user(user)
response = Response({'message': 'Login successful.'}, status=status.HTTP_200_OK)
response.set_cookie('jwt_token', str(refresh.access_token))
response.set_cookie('refresh_token', str(refresh))
return response
else:
return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)
here is my api for get user profile
@api_view(['GET'])
def get_user_profile(request):
if request.user.is_anonymous:
return Response({'error': 'User is not authenticated.'}, status=status.HTTP_401_UNAUTHORIZED)
user = request.user
profile = Profile.objects.get(user=user)
data = {
'username': user.username,
}
return Response(data, status=status.HTTP_200_OK)
my settings.py
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
}
my frontend code:
axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true})
.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
})
;