'CSRF verification failed with 403 error when deployed to AWS elastic beanstalk

After creating a Django project in local, where we tested that all the functionality was working as expected, we finally deployed it in Amazon Web Services Beanstalk. But to our dismay, the production app was showing CSRF error which was never seen during the development phase.

CSRF Verification Error

Here is a sample of the code:

models.py

class CustomerAccount(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    phone_number = models.CharField(max_length=50,blank=True)
    first_name = models.CharField(max_length=200, null=True,blank=True)
    last_name = models.CharField(max_length=200, null=True,blank=True)


urls.py

urlpatterns = [
    path('', views.index, name='customer-index'),
]

views.py

@login_required(login_url="/login/")
def index(request):

    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('customers:customer-index')

    else:
        form = CustomerForm()

    context= {
        'form': form,
    }
    
    return render(request, 'customers/index.html', context)  

index.html


<div class="col-md-4">
    <div class="card p-3 mb-4 mx-2">
        <h3 class="text-center">New Customer</h3>
        <hr>
        <form method="POST" action="{% url 'customers:customer-index' %}">
            {% csrf_token %}
            {{ form|crispy }}
            <input class="btn btn-success btn-block" type="submit" value="Add Customer">
        </form>
    </div>
</div>

Additional details about our configuration:

  • Inside the settings.py, the middleware for CSRF has been added
MIDDLEWARE = [
   ...
   'django.middleware.csrf.CsrfViewMiddleware',
   ...

]


While we did go through some of the solutions that we could find such as
  • adding @csrf_exempt before the views function
  • setting the csrf token age to None
  • added action attribute in the form tag

but despite all these efforts, the beanstalk is still showing the same error.


Some things that we noticed with the error is:

  • The csrf issue automatically gets solved periodically after some time.
  • The templates for some of the views have older/previous id and doesn't have the updated primary key value when object with same details are added one after the other.


Solution 1:[1]

In my case, the issue was caused due to the caching issue on my cloudfront distribution. I needed to check the option to forward cookies.enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jayasai amerineni