Google OAuth2 регистрация в Django: ошибка «плохой запрос» при первой попытке регистрации
Я работаю над интеграцией входа/регистрации Google OAuth2 с Django, но я сталкиваюсь с проблемой во время первой попытки регистрации.
Поток:
-
Новая регистрация пользователя с использованием Google.
-
Пользователь нажимает кнопку «Войти с Google».
-
Пользователь перенаправлен на экран согласия Google OAuth2 и входит в систему.
-
После успешной регистрации Google перенаправляется в мое приложение с плохим запросом -
"POST /api/v1/auth/google/ HTTP/1.1" 400 Bad Request
: это происходит только в первый раз, когда пользователь пытается зарегистрироваться, он возвращает ошибку «плохой запрос». Проблема возникает только во время первой регистрации, даже если пользовательские данные добавляются в базу данных. -
Если я попытаюсь вернуться с той же учетной записью, используя Google, теперь я смогу успешно войти в систему.
Соответствующий код:
Backend/api/urls.py:
path('auth/google/', GoogleLogin.as_view(), name='google_login')
backend/api/views.py:
from django.conf import settings
from django.http import HttpResponseRedirect
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from dj_rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
client_class = OAuth2Client
callback_uri = settings.REDIRECT_URI
def get(self, request):
return HttpResponseRedirect(redirect_to=settings.GOOGLE_AUTH_URL)
backend/api/adapter.py:
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from api.models import User
class CustomSocialAdapter(DefaultSocialAccountAdapter):
def pre_social_login(self, request, sociallogin):
# Ignore existing social accounts, just do this stuff for new ones
if sociallogin.is_existing:
return
# some social logins don't have an email address, e.g. facebook accounts
# with mobile numbers only, but allauth takes care of this case so just
# ignore it
if 'email' not in sociallogin.account.extra_data:
return
# check if given email address already exists.
# Note: __iexact is used to ignore cases
try:
email = sociallogin.account.extra_data['email'].lower()
existing_user = User.objects.get(email__iexact=email)
# if it does not, let allauth take care of this new social account
except User.DoesNotExist:
return
# if it does, connect this new social login to the existing user
sociallogin.connect(request, existing_user)
любая помощь будет высоко оценена!
Adding the below block resolved the issue.
@csrf_exempt # This decorator exempts CSRF protection for the POST request
def post(self, request, *args, **kwargs):
return super().post(request, *args, **kwargs)