skip to Main Content

The error occurs in this react code

const headers = new Headers({
    "X-CSRFToken": Cookies.get('csrftoken')
}); 
const response = await fetch("api/signinUser",
      {
        method: "POST",
        headers: headers,
        body: formData
      });     

Trying to access this Django Api

@ensure_csrf_cookie
def signin(request):
    if request.method == 'POST':
        auth = False
        username = request.POST['username']
        password = request.POST['password']
        
        user = authenticate(username=username, password=password)
        print("Authenticating User", user)
        if user is not None:
            auth = True
            login(request, user) # Does this return anything?
        ret = {
            "auth": auth
        }
        print("RET", ret)
        return JsonResponse(ret)

I have django.middleware.csrf.CsrfViewMiddleware in my MIDDLEWARE variable

I’m running my Django server in an AWS EC2 instance that I access with http://<my public ip>:8000/

3

Answers


  1. headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'csrftoken': Cookies.get('csrftoken'),
    },
    
    Login or Signup to reply.
  2. As you are accessing using HTTP (and not https) you need to ensure the cookies are not https only (i.e. "Secure").

    The "easiest" for this it to changes your settings to ensure that http cookies will work (https://docs.djangoproject.com/en/4.1/ref/settings/#csrf-cookie-httponly, https://docs.djangoproject.com/en/4.1/ref/settings/#csrf-cookie-secure and https://docs.djangoproject.com/en/4.1/ref/settings/#session-cookie-httponly).

    However, as you’re on AWS, it’s fairly easy and cheap to access over HTTPS with a valid certificate if you have a (sub)domain name you can use.

    • Create yourself a Load Balancer (in the EC2) panel). That prompts you to…
    • Create a "Target Group". The target group contains the instance above
    • Set it so that a listener on "443" will redirect traffic to "80" on your instance (so your instance does not need a certificate). In doing this, you’ll be prompted to create a certificate within AWS.
    • Point your DNS to the load balancer.

    Please check costs, but the normally-expensive part (the certificate) is free, and you can set security groups to lock users our of having direct access to your EC2.

    Login or Signup to reply.
  3. You should check out the docs.

    https://docs.djangoproject.com/en/4.1/ref/csrf/

    A hidden form field with the name ‘csrfmiddlewaretoken’, must be present in all outgoing POST forms.

    They are referring to a hidden input field within your form.

    For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search