Home > Software engineering >  Django and React: csrf cookie is not being set in request header
Django and React: csrf cookie is not being set in request header

Time:06-01

To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided:

settings.py:

ALLOWED_HOSTS = ['*']
ACCESS_CONTROL_ALLOW_ORIGIN = '*'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_METHODS = '*'
ACCESS_CONTROL_ALLOW_HEADERS = '*'

'''
SESSION_COOKIE_SECURE = True
'''
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'


CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000",'http://127.0.0.1:8000','http://localhost:3000']

setting SAMESITE protocol to anything else haven't made any change

in views.py, we have login view (class based):

class LoginView(views.APIView):
    permission_classes = [AllowAny,]
    serializer_class = serializer.LoginSerializer
    def post(self,request):
        data = serializer.LoginSerializer(data=request.data)
        print(data.is_valid())
        if data.is_valid():
            email = data.data['email']
            password = data.data['password']
            auth = authenticate(username=email,password=password)
            if auth:
                login(request,auth)
                return HttpResponse("Success",status=200)
            else:
                print(password == "")
                if email == "" and password =="":
                    return HttpResponse('Both email and password field are empty',status=400)

                elif email == "":
                    return HttpResponse('Email field is empty',status=400)
                elif password == "":
                    return HttpResponse('Passowrd field is empty',status = 400)
        else:
            return HttpResponse("Both email and password fields are empty",status=400)

in serializer.py, we got the login serializer:

class LoginSerializer(serializers.Serializer):
    email = serializers.CharField(required=False)
    password = serializers.CharField(required=False,allow_null=True,allow_blank=True)

in react (frontend side), here is how i am making a post request:

function Login(){
    const [login,setLogin] = useState({'email':'','password':''})
    const {email,password} = login
    const navigate = useNavigate()

    let handleChange = (e)=>{
        setLogin(
            {
                ...login,
                [e.target.name]:e.target.value
            }
        )

    }

    
    let handleSubmit = (e)=>{
        e.preventDefault()
        axios.post('http://127.0.0.1:8000/login/',login,{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then(
            (res)=>{

 
                    console.log(res)
                    console.log(Cookies.get('csrftoken')) //undefined here

            }
        ).catch((e)=>{
    console.log(e)
            }
        })

    }
}

this is part of the code btw ^.

edit: I have a csrf view too, not sure how to use it:

class GetCSRFToken(views.APIView):
    permission_classes = [AllowAny, ]

    def get(self, request, format=None):
        return Response({ 'success': 'CSRF cookie set' })

any help is welcomed.

CodePudding user response:

I suggest to you that try to work with your both servers using HTTPS. Some help: Django

To ReactJS simply use the same certificates generated to use in Django to tun the server with next command:

HTTPS=true SSL_CRT_FILE=path/server.crt SSL_KEY_FILE=path/server.key npm start

This with the goal of change your settings:

CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SAMESITE = 'Strict'  
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = [ "https://127.0.0.1:3000", ...] 

But is not totally necessary.

Now, your view GetCSRFToken is incorrect because return a message. This an example that I have implemented. The key is the decorator ensure_csrf_cookie

Views.py:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie

class CsrfTokenView(APIView):
"""Send to the login interface the token CSRF as a cookie."""

    @method_decorator(ensure_csrf_cookie)
    def get(self, request, *args, **kwargs) -> Response:
        """Return a empty response with the token CSRF.

        Returns
        -------
        Response
            The response with the token CSRF as a cookie.
        """
        return Response(status=status.HTTP_204_NO_CONTENT)

In ReactJS just code a useEffect with empty dependencies to do the request just after mount the component.

useEffect(() => {
    axios.get('/url/csrf-token/', {
            headers: { 'Authorization': null },
            withCredentials: true,
        }
    ).catch( () => {
        alert('Error message.');
    });
}, []);

At this point, you will be able to watch the cookie in 'developer tools'. Finally, in your LoginView add the csrf_protect decorator to your post method to make sure the endpoint needs the CSRF_TOKEN.

Views.py:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
...

class LoginView(views.APIView):
    ...
    @method_decorator(csrf_protect)
    def post(self,request):
        # code

Don't forget map the url of the csrf view and put the correct in the request (useEffect).

Also in your request of login, add withCredentials: true. This way the request sent the cookies (CSRF). Django is going to compare the header X-CSRFToken with the value of the cookie received and if match, it is going to execute the method body.

I think that's it. Let me know if it works.

  • Related