[Python] dj_rest_auth SocialLoginView error "Failed to exchange code for access token"

Discussão em 'Python' iniciado por Stack, Junho 2, 2025.

  1. Stack

    Stack Membro Participativo

    I have configured social login with Google with dj-rest-auth and Django rest framework. When I try to pass the authentication code to my endpoint, I get a 400 error: Request

    {
    "code": "4%google-auth-code"
    }


    Response

    {
    "non_field_errors": [
    "Failed to exchange code for access token"
    ]
    }


    Here is my code. settings.py file:


    INSTALLED_APPS = [
    ...
    'django.contrib.sites',

    'rest_framework',
    'rest_framework.authtoken',

    'dj_rest_auth',
    'dj_rest_auth.registration',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    ...

    ]

    MIDDLEWARE = [
    ...

    'allauth.account.middleware.AccountMiddleware',
    ]

    SITE_ID = 1
    SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'my_social_key'
    SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'google_secret'
    SOCIALACCOUNT_PROVIDERS = {
    'google': {
    'APP': {
    'client_id': SOCIAL_AUTH_GOOGLE_OAUTH2_KEY,
    'secret': SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,
    },
    }
    }

    AUTHENTICATION_BACKENDS = [
    'allauth.account.auth_backends.AuthenticationBackend',
    ]

    REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework.authentication.TokenAuthentication',
    ]
    }


    user/urls.py

    from django.urls import path
    from user import views

    app_name = 'user'

    urlpatterns = [
    ...
    path('auth/google/', views.GoogleLogin.as_view(), name='google_login'),
    ...
    ]


    user/views.py

    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
    callback_url = 'http://localhost:8000/api/auth/google/'
    client_class = OAuth2Client


    **requirements.txt **

    dj-rest-auth==6.0.0django-allauth==0.61.0


    Google Cloud Console is working properly. Redirect url is also fine

    enter image description here

    I tried to catch this error from the module dj-rest-auth, but even there the information is superficial:

    `Error retrieving access token: b'{\n "error": "invalid_grant",\n "error_description": "Malformed auth code."\n}'`

    Continue reading...

Compartilhe esta Página