[FIXED] Django + DRF: 403 FORBIDDEN: CSRF-Token fehlt oder ist falsch

Ausgabe

Ich habe eine Android-Client-App, die versucht, sich bei einem Django + DRF-Backend zu authentifizieren. Wenn ich mich jedoch anmelden möchte, bekomme ich folgende Antwort:

403: CSRF Failed: CSRF token missing or incorrect.

Die Anfrage wird an http://localhost/rest-auth/google/folgende Stelle gesendet:

access_token: <the OAuth token from Google>

Was könnte das verursachen? Der Client hat kein CSRF-Token, da der POST zur Authentifizierung das erste ist, was zwischen dem Client und dem Server passiert. Ich habe viele der früheren Fragen mit demselben Problem überprüft, aber ich konnte keine Lösungen finden.

Die relevanten Einstellungen auf der Django-Seite lauten wie folgt:

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend"
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.request",
    "django.contrib.auth.context_processors.auth",
    "allauth.account.context_processors.account",
    "allauth.socialaccount.context_processors.socialaccount"
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.google',

    'django.contrib.admin',

    # REST framework
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ( 
        'rest_framework.permissions.IsAuthenticated'
    ),
}

Lösung

Dummkopf, ich habe das TokenAuthenticationFramework aus den REST-Einstellungen verpasst:

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

Jetzt funktioniert es genauso wie gedacht.


Beantwortet von –
manabreak


Antwort geprüft von –
Cary Denson (FixError Admin)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like