I am having difficulty to get csrftoken stored in Django session using React

25 Views Asked by At

I am having a hard time here, and I'm not sure what I'm doing wrong so far. I am working on CS50W Project 4 with Django and React. Django is handling the registration process for both the front end and back end. However, I want to fetch the CSRF token stored in the session in my React app when the user logs in.

Please advise if you have any insights into what might be causing this issue. Thank you.

To achieve this, I installed "pip install django-cors-headers." I believe I have also completed the necessary configurations. Here are some screenshots

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


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


DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = False
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://192.168.8.101:3000",
    "http://127.0.0.1:8000"  
]

I created a view to return the CSRF token in JSON form. My login view is shown below. In the React app, my code includes the following: method: 'GET', credentials: 'include',

def get_token(request):
    csrftoken = request.COOKIES.get('csrftoken')
    return JsonResponse({'token':csrftoken}) # to return api
fetch('http://localhost:8000/get_token/', {  
    method: 'GET',  
    credentials: 'include', 
})  
.then(response => response.json())  
.then(data => console.log(data));  
 
it always returns 
"{token: null}"

from django.middleware.csrf import get_token  


def login_view(request):  
    # ... some existing code ...  
    if user is not None:  
        # ... some existing code ...  
        # Get or create CSRF token  
        csrftoken = get_token(request)  
        # Set CSRF token in cookie  
        response.set_cookie('csrftoken', csrftoken, secure=False, httponly=False)  
        return response  

However, I am still not receiving the CSRF token in the React app. Meanwhile, I can easily obtain the CSRF token using the Django URL. with my react app it always returns "{token: null}"

0

There are 0 best solutions below