Apple使用allauth和rest-auth登录django rest框架

Apple login in django rest framework with allauth and rest-auth

我已经在 django 中使用 allauth 和 rest-auth 实现了 Apple 登录。我实现了与 Google 登录相同的方式,效果很好。

views.py

class AppleLogin(SocialLoginView):
    adapter_class = AppleOAuth2Adapter

urls.py

urlpatterns = [
    path("auth/apple/", AppleLogin.as_view(), name="apple-login"),
]

pip 版本

Django==2.2.17
django-allauth==0.43.0
django-rest-auth==0.9.3
djangorestframework==3.8.2
djangorestframework-jwt==1.11.0

当我进行如下测试时,我得到 KeyError: 'id_token',这就是错误的来源:https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/providers/apple/views.py#L92

我不知道如何解决这个错误。

感谢您的帮助!

curl -X POST 'https://.../auth/apple/' \
              -d 'access_token=AUTHENTICATION_CODE'

or

curl -X POST 'https://.../auth/apple/' \
              -d 'id_token=ID_TOKEN'   \
              -d 'access_token=AUTHENTICATION_CODE'

使用这个自定义序列化器类。 https://github.com/pennersr/django-allauth/pull/2424#issuecomment-651913243

看来问题出在django-rest-auth 您的身份验证视图应如下所示

from allauth.socialaccount.providers.apple.views import AppleOAuth2Adapter
from allauth.socialaccount.providers.apple.client import AppleOAuth2Client
from rest_auth.registration.views import SocialLoginView

class AppleLogin(SocialLoginView):
    adapter_class = AppleOAuth2Adapter
    callback_url = 'https://anycallbackurlhere'
    client_class = AppleOAuth2Client
    serializer_class = CustomAppleSocialLoginSerializer

SerializerClass 的唯一变化是在 validate 函数中,因此您可以重写该方法

from rest_auth.registration.serializers import SocialLoginSerializer

class CustomAppleSocialLoginSerializer(SocialLoginSerializer):
    def validate(self, attrs):
        .... #copy the method from the link above