1

I have built the frontend with react and backend with django and everything works fine on localhost but when I deployed the frontend on heroku and made a POST request to login (backend running on localhost still)I got the following error:

Forbidden (CSRF cookie not set.): /login/

Front end code:

https://pastebin.com/CHArh4JL

function getCsrf(){
        fetch("http://localhost:8000/csrf/", {
                credentials: "include",
              })
              .then((res) => {
                let csrfToken = res.headers.get("X-CSRFToken");
                setCsrf({csrf: csrfToken});
                
              })
              .catch((err) => {
                console.log(err);
              })
              
    }

    const login = (event) => {
        event.preventDefault();
        setIsLoading(true)
        fetch("http://localhost:8000/login/", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrf.csrf,
          },
          credentials: "include",
          body: JSON.stringify({username: username, password: password}),
        })
        .then(isResponseOk)
        .then((data) => {
          console.log(data);
          setIsAuthenticated(true)
          localStorage.setItem("authenticated", true);
          setUsername('')
          setPassword('')
          setIsLoading(false)
        //   this.setState({isAuthenticated: true, username: "", password: ""});
        })
        .catch((err) => {
            console.log('inside login catch')
            console.log(csrf.csrf, 'catch')
          console.log(err);
        });
        
      }

      const isResponseOk = (response) =>{
        if (response.status >= 200 && response.status <= 299) {
          return response.json();
        } else {
          console.log(response)
          throw Error(response.statusText);
        }
      }
      useEffect(() => {
        //getSessions
        setIsLoading(true)
        fetch("http://localhost:8000/session/", {
            credentials: "include",
          })
          .then((res) => res.json())
          .then((data) => {
            // console.log(data);
            if (data.isAuthenticated) {
              setIsAuthenticated(true)
              
              console.log(data)
            } else {
                // test()
              setIsAuthenticated(false)
              console.log(data)
                
              getCsrf()
            }
            setIsLoading(false)
          })
          .catch((err) => {
            console.log(err);
          });
        
       
      }, [])
      
   

backend code:

https://pastebin.com/sXv1AWhK

@require_POST
# @csrf_exempt
def login_view(request):
   
    print(request.body)
    data = json.loads(request.body)
    print(data)
    username = data.get('username')
    password = data.get('password')
    # username = None
    # password = None
    # newUser = DjangoUser(username="test", password="test")
    # newUser.save()

    if username is None or password is None:
        return JsonResponse({'detail': 'Please provide username and password.'}, status=400)

    user = authenticate(username=username, password=password)

    if user is None:
        return JsonResponse({'detail': 'Invalid credentials.'}, status=400)

    login(request, user)
    return JsonResponse({'detail': 'Successfully logged in.'})

@ensure_csrf_cookie
def session_view(request):
    if not request.user.is_authenticated:
        return JsonResponse({'isAuthenticated': False})

    return JsonResponse({'isAuthenticated': True})

Here are my settings.py

https://pastebin.com/nqRVy6ty

"""
Django settings for ecommerce project.

Generated by 'django-admin startproject' using Django 3.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    "corsheaders.middleware.CorsMiddleware",
    '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',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'ecommerce.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ecommerce.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
       #database stuff here
        'CONN_MAX_AGE': None,
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = ['https://theherokuweb.herokuapp.com','http://theherokuweb.herokuapp.com','http://localhost:3000','https://*.127.0.0.1']


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATED_CLASSES': [
        'rest_framework.authenticated.SessionAuthentication',
    ]
}

CSRF_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SAMESITE = 'Lax'
# CSRF_COOKIE_HTTPONLY = True
# SESSION_COOKIE_HTTPONLY = True

# PROD ONLY
# CSRF_COOKIE_SECURE = True
# SESSION_COOKIE_SECURE = True

CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken']
CORS_ALLOW_CREDENTIALS = True

Edit: I have now deployed both the react frontend and django backend separately but still getting the [Forbidden (403) CSRF verification failed. Request aborted.] error.

sash
  • 101
  • 7

1 Answers1

0

It is because in settings.py you have set CSRF_COOKIE_SECURE = True and also you have set CSRF_COOKIE_HTTPONLY = True.You can refer CSRF_COOKIE_SECURE and CSRF_COOKIE_HTTPONLY documentation. Hope this answer will be of some help to you.

  • 1
    I have commented them out in settings.py. I did come across that answer and tried it but it did not work. – sash Oct 10 '22 at 08:52