简体   繁体   中英

How should I go building login serializer & View which uses DRF for Token Authentication?

This is how my Signup Serializer looks like

class AuthUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = AuthUser
        fields = ('first_name', 'last_name', 'email', 'password', 'role')
    
    def create(self, data):
        return AuthUser.objects.create(**data)

Here is the view of it:

class Signup(CreateAPIView):
    serializer_class = AuthUserSerializer
    queryset = AuthUser.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        headers = self.get_success_headers(serializer.data)
        token, created = Token.objects.get_or_create(user=serializer.instance)
        return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers)

And data is getting inserted in DATA successfully, and token is being generated properly. Now I want to make login endpoint where user will enter his email and password and if true return the token. Kindly assist me, on how should I go building this login serializer & view.

Are you sure you have to do it? DRF provides full authentication model and you don't need to build it by yourself. If you want customize it, use inheritance.

in settings.py define auth classes (in your case, use TokenAuthentication)

...
INSTALLED_APPS = [
    ...
    'rest_framework.authtoken'
]

in urls.py add auth url:

from rest_framework.authtoken import views
urlpatterns += [
    path('api-token-auth/', views.obtain_auth_token)
]

If you want to customize authentication, inherit from DRF ObtainTokenAuth:

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })

and then change your urls.py

urlpatterns += [
    path('api-token-auth/', CustomAuthToken.as_view())
]

Read more in DRF documentation:https://www.django-rest-framework.org/api-guide/authentication/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM