使用allauth和rest-auth在Django Rest Framework中实现苹果登录

4

我使用allauth和rest-auth在Django中实现了苹果登录。这与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'
1个回答

1
使用这个自定义的序列化类。 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

@Ben和@Jonabc7你们好,我已经尝试过这个方法,但是我遇到了错误 from allauth.socialaccount.providers.Apple.views import AppleOAuth2Adapter ModuleNotFoundError: No module named 'allauth.socialaccount.providers.Apple' - Kwall
2
@Kwall 你需要将django-allauth更新到0.43.0或更高版本。苹果提供商已在0.43.0版本中添加。你可以在这里查看发布说明:https://django-allauth.readthedocs.io/en/latest/release-notes.html#id2 - Ben
@Ben 是的,现在它可以工作了,非常感谢你。 - Kwall
我尝试了相同的方式,但是在回调URL上没有被重定向。 - Naazneen Jatu

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