Search code examples
djangodjango-rest-frameworkdjango-usersdjango-rest-framework-simplejwt

How can I use email instead of username in djangoreostframework-simplejwt?


I am going to use email instead of username when I get access token and refresh token using djangoreostframework-simplejwt. So after writing the code, I could access my browser and confirm that the field that was username was renamed to email.But when I post the email of user in email field, the following error appears.

"detail": "No active account found with the Given Credentials"

Can you tell me what is wrong with my code? Here is my code.

Serializers.py

from rest_framework_simplejwt.serializers import TokenObtainSerializer
from django.contrib.auth.models import User

class EmailTokenObtainSerializer(TokenObtainSerializer):
    username_field = User.EMAIL_FIELD


class CustomTokenObtainPairSerializer(EmailTokenObtainSerializer):
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        data["refresh"] = str(refresh)
        data["access"] = str(refresh.access_token)

        return data

views.py

from rest_framework_simplejwt.views import TokenObtainPairView
from .serializers import CustomTokenObtainPairSerializer

class EmailTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

thanks


Solution

  • You override the validate function of the class CustomTokenObtainPairSerializer. In the Validate function, you call the validate super(). In TokenObtainSerializer the validate function uses the Django authenticate function. That uses a username and password to validate the user. You might want to create a custom authentication backend that uses email to authenticate.