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

时间:2022-04-27 03:42:18

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 post request sending username and password.

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

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

(api/api-token-auth/ is the url configured with the obtain_auth_token view)

(api / api-token-auth /是使用obtain_auth_token视图配置的url)

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

and the response is the user token.

并且响应是用户令牌。

{"token":"c8a8777aca969ea3a164967ec3bb341a3495d234"}

I need to obtain the user token auth using email-password on the post instead username-password, or both. I was reading the documentation of custom authentication http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication... but really, isn't very clear to me. It's very helpful to me... thanks :).

我需要在帖子上使用电子邮件密码而不是用户名密码来获取用户令牌身份验证,或两者兼而有之。我正在阅读自定义身份验证的文档http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication ...但实际上,对我来说并不是很清楚。这对我很有帮助...谢谢:)。

3 个解决方案

#1


23  

Ok,I found a way for get the auth token using email or username... This is the serializer:

好的,我找到了使用电子邮件或用户名获取身份验证令牌的方法......这是序列化程序:

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

In the email_or_username field, the user can send the email or the username, and using the function validateEmail(), we can check if the user is trying to login using email or username. Then, we can make the query for get the user instance if is valid, and authenticate it.

在email_or_username字段中,用户可以发送电子邮件或用户名,并使用validateEmail()函数,我们可以检查用户是否尝试使用电子邮件或用户名登录。然后,如果有效,我们可以进行查询以获取用户实例,并对其进行身份验证。

This is the view.

这是观点。

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)

and then:

接着:

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

It's ready.

准备好了。

#2


3  

Write these requirements into your settings.py

将这些要求写入settings.py

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

To check, send this json format request to your server:

要检查,请将此json格式请求发送到您的服务器:

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

#3


1  

There is a cleaner way to get the user token.

有一种更清晰的方式来获取用户令牌。

simply run manage.py shell

只需运行manage.py shell

and then

接着

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


23  

Ok,I found a way for get the auth token using email or username... This is the serializer:

好的,我找到了使用电子邮件或用户名获取身份验证令牌的方法......这是序列化程序:

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

In the email_or_username field, the user can send the email or the username, and using the function validateEmail(), we can check if the user is trying to login using email or username. Then, we can make the query for get the user instance if is valid, and authenticate it.

在email_or_username字段中,用户可以发送电子邮件或用户名,并使用validateEmail()函数,我们可以检查用户是否尝试使用电子邮件或用户名登录。然后,如果有效,我们可以进行查询以获取用户实例,并对其进行身份验证。

This is the view.

这是观点。

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)

and then:

接着:

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

It's ready.

准备好了。

#2


3  

Write these requirements into your settings.py

将这些要求写入settings.py

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

To check, send this json format request to your server:

要检查,请将此json格式请求发送到您的服务器:

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

#3


1  

There is a cleaner way to get the user token.

有一种更清晰的方式来获取用户令牌。

simply run manage.py shell

只需运行manage.py shell

and then

接着

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