Tags - csrf

Modern Vanilla JS for cookie parsing

In a previous post I wrote a Vanilla JS function for parsing all the current cookies. Since then a couple of things have happened:

  1. I realised it was not safe
  2. JS in browsers got better [and I got better at it]

It was not safe in as much as it parsed the cookie value once and retained the value. If you were, for instance, using a SPA, Django might update the CSRF token at any point, making your value stale. So instead, I've updated the function to get just one value, and perform parsing on each call.

The simplest API

So, I saw a post recently about Build an API under 30 lines of code using Flask.

I started wondering what it would take to do the same in Django.

The two main tools we're going go use are JsonResponse and ModelForm.

Vanilla JS meets Django's CSRF

I was recently helping someone who was trying to learn about building web sites, and was trying to avoid learning too many things at once, so opted to avoid JS libraries for now.

As the discussion progressed, they ran into Django's Cross Site Request Forgery protection which stumped them.

So, as I was about to link them to the part of the docs that shows how to add the CSRF token from the cookie to your headers, I realised it all assumes you're using jQuery.