Django rest framework: Obtain auth token using email instead username

前端 未结 4 1736
有刺的猬
有刺的猬 2020-12-24 08:39

I\'m working on a project to enable the django rest framework authentication for mobile devices. I\'m using the default token authentication for get the user token from a po

4条回答
  •  生来不讨喜
    2020-12-24 09:28

    Change the default serializer the library is using for example in auth/serializers.py

    from django.contrib.auth import authenticate
    from django.utils.translation import gettext_lazy as _
    
    from rest_framework import serializers
    
    
    class MyAuthTokenSerializer(serializers.Serializer):
        email = serializers.EmailField(label=_("Email"))
        password = serializers.CharField(
            label=_("Password",),
            style={'input_type': 'password'},
            trim_whitespace=False
        )
    
        def validate(self, attrs):
            email = attrs.get('email')
            password = attrs.get('password')
    
            if email and password:
                user = authenticate(request=self.context.get('request'),
                                    email=email, password=password)
    
                # The authenticate call simply returns None for is_active=False
                # users. (Assuming the default ModelBackend authentication
                # backend.)
                if not user:
                    msg = _('Unable to log in with provided credentials.')
                    raise serializers.ValidationError(msg, code='authorization')
            else:
                msg = _('Must include "username" and "password".')
                raise serializers.ValidationError(msg, code='authorization')
    
            attrs['user'] = user
            return attrs
    

    Override the view for example in auth/views.py

    from rest_framework.authtoken import views as auth_views
    from rest_framework.compat import coreapi, coreschema
    from rest_framework.schemas import ManualSchema
    
    from .serializers import MyAuthTokenSerializer
    
    
    class MyAuthToken(auth_views.ObtainAuthToken):
        serializer_class = MyAuthTokenSerializer
        if coreapi is not None and coreschema is not None:
            schema = ManualSchema(
                fields=[
                    coreapi.Field(
                        name="email",
                        required=True,
                        location='form',
                        schema=coreschema.String(
                            title="Email",
                            description="Valid email for authentication",
                        ),
                    ),
                    coreapi.Field(
                        name="password",
                        required=True,
                        location='form',
                        schema=coreschema.String(
                            title="Password",
                            description="Valid password for authentication",
                        ),
                    ),
                ],
                encoding="application/json",
            )
    
    
    obtain_auth_token = MyAuthToken.as_view()
    

    Hook up the url for example in auth/urls.py

    from .views import obtain_auth_token
    urlpatterns = [
        re_path(r'^api-token-auth/', obtain_auth_token),
    ]
    

    and you are ready to go!!

提交回复
热议问题