i want to set up a simple Django Backend with a rest api. If i'am trying to login with the supplied urls, but everytime i try to login i get a 403 error: CSRF Verficatoin failed. CSRF cookie not set.
This are my used apps:
Django==4.1.10
# Rest Framework
djangorestframework==3.14.0
djangorestframework-api-key==2.3.0
djangorestframework-simplejwt==5.2.2
markdown==3.4.4
# CORS for rest api
django-cors-headers==4.2.0
and my settings:
ALLOWED_HOSTS='*, localhost'
ALLOWED_ORIGINS='http://*, https://*'
CSRF_COOKIE_AGE=31449600
CSRF_COOKIE_NAME='csrftoken'
CSRF_USE_SESSIONS=False
CSRF_TRUSTED_ORIGINS='http://*, https://*'
CSRF_COOKIE_HTTPONLY=False
CSRF_COOKIE_SECURE=False
CSRF_COOKIE_DOMAIN = None
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CORS_ALLOW_ALL_ORIGINS=False
CORS_ALLOWED_ORIGIN_REGEXES=''
CORS_ALLOWED_ORIGINS='http://localhost:8888, http://127.0.0.1:8888'
the server runs on port 8888 with the command: python3 manage.py runserver 0.0.0.0:8888
The Middleware:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
and the Settings for the Rest Framework:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework_api_key.permissions.HasAPIKey',
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
# 'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
# 'rest_framework.authentication.BasicAuthentication', # only for testing
],
"DEFAULT_PARSER_CLASSES": [
"rest_framework.parsers.JSONParser",
"rest_framework.parsers.FormParser",
"rest_framework.parsers.MultiPartParser",
],
}
and these urls are in the introduction of the app:
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
and now, if i try following request:
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{"username": "my_username", "password": "my_password"}' \
http://localhost:8888/api/token/
i get the error code 403, as described above.
Do you have any ideas, how can i solve the problem?
Best regards!