Django rest框架:使用电子邮件而不是用户名获取身份验证令牌

22

我正在开发一个项目,旨在为移动设备启用Django Rest框架身份验证。我使用默认的令牌身份验证来获取用户令牌,从一个发送用户名和密码的POST请求中获取。

curl --data "username=username&password=password" http://127.0.0.1:8000/api/api-token-auth/

(api/api-token-auth/ 是配置了 obtain_auth_token 视图的URL)

urlpatterns = [
    url(r'^api/api-token-auth/', obtain_auth_token),
    url(r'^', include(router.urls)),
]

响应是用户令牌。

{"token":"c8a8777aca969ea3a164967ec3bb341a3495d234"}

我需要通过电子邮件密码在发送帖子时获取用户令牌认证,而不是用户名密码或同时使用两者。我正在阅读自定义身份验证的文档http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication,但对我来说并不是很清楚。


你的应用程序是否已经有使用电子邮件和密码登录的方式?还是这是你为应用程序实施的第一种身份验证方法? - Daniel Robinson
嗨...这是第一种身份验证方法,我还没有实现其他的...现在我正在使用默认的获取令牌方法,使用用户名和密码...但是,在移动设备上,我需要使用电子邮件和密码来获取令牌认证。 - Andrés Quiroga
4个回答

41

好的,我找到了一种通过电子邮件或用户名获取授权令牌的方法... 这是序列化器:

class AuthCustomTokenSerializer(serializers.Serializer):
    email_or_username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, attrs):
        email_or_username = attrs.get('email_or_username')
        password = attrs.get('password')

        if email_or_username and password:
            # Check if user sent email
            if validateEmail(email_or_username):
                user_request = get_object_or_404(
                    User,
                    email=email_or_username,
                )

                email_or_username = user_request.username

            user = authenticate(username=email_or_username, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise exceptions.ValidationError(msg)
            else:
                msg = _('Unable to log in with provided credentials.')
                raise exceptions.ValidationError(msg)
        else:
            msg = _('Must include "email or username" and "password"')
            raise exceptions.ValidationError(msg)

        attrs['user'] = user
        return attrs

在"email_or_username"字段中,用户可以发送电子邮件或用户名,并使用validateEmail()函数检查用户是否尝试使用电子邮件或用户名登录。然后,如果有效,我们可以查询获取用户实例并进行身份验证。这是视图。
class ObtainAuthToken(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (
        parsers.FormParser,
        parsers.MultiPartParser,
        parsers.JSONParser,
    )

    renderer_classes = (renderers.JSONRenderer,)

    def post(self, request):
        serializer = AuthCustomTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)

        content = {
            'token': unicode(token.key),
        }

        return Response(content)

然后:

curl --data "email_or_username=emailorusername&password=password" http://127.0.0.1:8000/api/my-api-token-auth/.

它已准备好。


1
你好!我尝试了你的解决方案,但它报错说缺少validateEmail和authenticate方法。你能分享一下缺失的代码吗?谢谢! - Alexey K

9

将这些要求写入您的settings.py文件

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

请发送以下 JSON 格式的请求到您的服务器进行检查:

{
    "username":"youremail@mail.domain",
    "password":"Pa$$w0rd"
}

4
这是DRF设置还是全局设置的一部分。 - Kairat Kempirbaev
3
我发现发送 JSON 并使用字段 "username",但值是电子邮件,仍然可以工作。不需要在 settings.py 中添加 ACCOUNT_。 - John Pang
4
看起来这是来自django-allauth而不是drf。 - agconti

7
更改库正在使用的默认序列化程序,例如在 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 "email" and "password".')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs

覆盖例如在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()

将示例中的URL与auth/urls.py进行连接

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

你已经准备就绪了!!


0

有一种更简洁的方法来获取用户令牌。

只需运行manage.py shell

然后执行以下操作

from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
u = User.objects.get(username='admin')
token = Token.objects.create(user=u)
print token.key

1
不适用于 Django <2.0 版本。 - migueloop
2
这是获取令牌的一种方式,但不是OP问题所问的。 - knopch1425
我认为这比那好得多。附言:您可以添加CSRF令牌。 - Shameer Kashif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接