Django rest-auth注册。如何在使用令牌认证时返回带有密钥的用户ID

7

我正在使用Django rest_auth.registration。

对应的urls.py中的条目为

url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))

我的认证类是rest_framework.authentication.TokenAuthentication。

这个rest API调用非常完美。

当我通过这个API进行注册时,我会得到以下响应。

{
  "key": "3735f13cd69051579156f98ffda338a2d7a89bb5"
}

我希望您能在响应中包含user_id字段。我该如何做呢?我尝试从类RegisterView(CreateAPIView)扩展方法get_response_data,但无法实现。请问有什么最佳实践可以实现这一点?最好提供代码。谢谢。
我想使用rest_auth.registration提供的rest-auth/registration/ URL。我不想为此创建一个单独的新URL。
我的Settings.py如下:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'sdAPI.apps.SdapiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_framework_swagger',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django_extensions',
]

# auth and allauth settings
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
    'SCOPE': ['email', 'publish_stream'],
    'METHOD': 'oauth2'  # instead of 'oauth2'
    }
}

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
    ),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
)
}

SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 
REST_SESSION_LOGIN = False

以下是我的urls.py文件

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/',include('rest_auth.registration.urls')),
]

请参考此问题,https://dev59.com/yaLia4cB1Zd3GeqPjHCe - zaidfazil
可能是如何在Django中使用令牌返回用户ID?的重复问题。 - Arpit Solanki
我想使用rest_auth.registration提供的开箱即用的rest-auth/registration/ url。我不想为此创建单独的新URL“认证”。 - Dilip Khemani
你能在settings.py文件中展示相关代码吗? - zaidfazil
已经更新了帖子中相关的代码。谢谢。 - Dilip Khemani
1个回答

13

我认为你只需要在你的REST_AUTH_SERIALIZERS配置中覆盖TOKEN_SERIALIZER选项。

from rest_framework.authtoken.models import Token

class TokenSerializer(serializers.ModelSerializer):

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

然后,按照文档中所示,在您的settings.py中进行设置,

REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
    'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
    ...
}

我不需要login_serializer设置,那是干什么用的? - Harry Moreno

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