Angular+Django CSRF token not being saved as cookie

Discussão em 'Angular' iniciado por bp-pet, Outubro 11, 2024.

  1. bp-pet

    bp-pet Guest

    I have a webapp with Angular frontend and Django backend. Everything works fine locally so I deployed the backend to PythonAnywhere. I use CSRF tokens so as soon the user opens the page, an empty request is sent to the backend, which responds with the token which is automatically saved as a cookie. However this does not work when I deploy the backend. I can see the token is in the response, but it does not appear in the browser storage, and it cannot be used for the following requests.

    I'm not sure how to even debug this. What could be causing this to begin with?

    This is the relevant part of my setttings.py:

    ALLOWED_HOSTS = ['*']

    # Application definition

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    ]

    MIDDLEWARE = [
    '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',
    'corsheaders.middleware.CorsMiddleware',
    ]

    CORS_ALLOWED_ORIGINS = (
    'http://localhost:4200',
    )

    CSRF_TRUSTED_ORIGINS = (
    'http://localhost:4200',
    )

    CORS_ALLOW_CREDENTIALS = True

    CSRF_COOKIE_SAMESITE = 'None'
    CSRF_COOKIE_SECURE = True


    I get the same problem when I deploy the frontend (then I also add it as a trusted origin but I skipped that in this extract).

    Like I said, I can see the token in the response in the browser network view, but it never reaches the browser storage. And it works fine when running the same backend locally.

    Continue reading...

Compartilhe esta Página