如何通过django rest authentication接收带令牌的用户名?

问题描述 投票:0回答:3

我正在使用django Django = 2.1.7和rest framework djangorestframework = 3.9.2这是我的登录网址

path('rest-auth/login', include('rest_auth.urls')),

当我输入用户名和密码时,我从rest API获得了令牌。但我希望我的用户细节如名称,ID等显示在我的反应组件中。请帮我怎样实现。我在StackOverflow上看到了很多答案,即使官方文档也没有描述性的https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

django python-3.x django-rest-framework authorization django-rest-auth
3个回答
1
投票

如果您使用rest-auth,您可以使用以下URL获取已登录用户的id,username,email,first_name和last_name:http://localhost:8000/rest-auth/user/


1
投票

提到的包提供了我们override the settings的能力 在登录过程中,响应来自TOKEN_SERIALIZERJWT_SERIALIZER。在您的情况下,我假设您没有使用JWT方法。 因此,根据您所需的结构创建一个新的序列化程序类,并使用REST_AUTH_SERIALIZERS设置字典将其连接起来。 这是一个样本

#serializer.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.authtoken.models import Token


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('id', 'username', 'email')


class MyCustomTokenSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Token
        fields = ('key', 'user')

在你的settings.py

REST_AUTH_SERIALIZERS = {
    'TOKEN_SERIALIZER': 'path.to.custom.MyCustomTokenSerializer',
    ...
    ...
}

-1
投票

一旦用户登录,就无法自动填充用户数据。您应该能够获取用户在登录过程中输入的用户名,将其保存在变量中,并在收到令牌后再进行另一个API调用以获取用户信息。

© www.soinside.com 2019 - 2024. All rights reserved.