简体   繁体   中英

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

I have implemented Apple login in django with allauth and rest-auth. I implemented same way as Google login which worked perfectly.

views.py

class AppleLogin(SocialLoginView):
    adapter_class = AppleOAuth2Adapter

urls.py

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

pip versions

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

When I test as below I'm getting KeyError: 'id_token' and this is where error comes from: https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/providers/apple/views.py#L92

I have no idea how to fix this error.

Thank you for your help !

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'

Use this custom serializerClass. https://github.com/pennersr/django-allauth/pull/2424#issuecomment-651913243

It seems that the problem is in django-rest-auth Your authentication view should look like this

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

The only change in the SerializerClass is in the validate function so you can just override that method

from rest_auth.registration.serializers import SocialLoginSerializer

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM