DEV Community

Piotr
Piotr

Posted on • Originally published at finloop.github.io on

Django Vue (Axios) Cors headers + CSFR tokens

Basic CORS and CSFR settings for Django Rest Framework (DRF) + Axios:

# Settings.py:
...

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",
]

CSRF_TRUSTED_ORIGINS  = [
    "http://localhost:5173",
]

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SAMESITE = "None"

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
    "accept",
    "authorization",
    "content-type",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
    "x-xsrf-token"]
...
Enter fullscreen mode Exit fullscreen mode

In Vuejs:

// axios config:
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true,
Enter fullscreen mode Exit fullscreen mode

Read what these do before using them. I'm not responsible for any security issues that may arise from using these settings.

Bugs I encountered:

Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)