django.contrib.auth.login() function not returning any user as logged in
You have to set the default auth class as session authenticate class in DRF settings. Read more about it here [1].
Session auth uses session id to identify the user. So you have to send the cookie based session id in the request. Read about session auth here [2].
for example:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication', # <-- set this class
]
}
Use this code:
def post(self, request, format = None):
serializer = UserLoginSerializer(data=request.data)
if serializer.is_valid():
user = authenticate(username=serializer.validated_data["username"], password=serializer.validated_data["password"])
if user:
return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED)
return Response("Invalid username/password", status=status.HTTP_401_UNAUTHORIZED)
return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)
But my recommendation is to use Token auth [3].
To use token auth 2 things will change:
- The default auth class in DRF settings
- When sending a request to any DRF API view you to send the Auth header as
Token <token-value>
Your post method and API views code will remain same.
[1] https://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme
[2] https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication
[3] https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
I am using DRF for login. You can check this serializers and login view.
serializers.py:
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**data)
if user and user.is_active:
return user
raise serializers.ValidationError("Incorrect Credentials")
login view:
class LoginAPIView(generics.GenericAPIView):
queryset = User.objects.all()
permission_classes = [AllowAny]
serializer_class = LoginSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
return Response({
"user": UserSerializer(user, context=self.get_serializer_context()).data,
"token": AuthToken.objects.create(user)[1]
})
settings.py rest framework classes :
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework.authentication.BasicAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
'knox.auth.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}