Skip to main content

Learning Backend WebDev, Log #3 - Cross Site Request Forgery

Wasn’t quite well today, so took it slow.

The Problem

The only thing I managed to learn was what Cross Site Request Forgery,(CSRF) is, and how Django helps protect against it.
The Wikipedia page describes it in painstaking detail, and if you want it described a bit more simply, the Jesse Ruderman does an admirable job.
Computerphile does an even better job.

I am using this analogy in my head.

I go and stay over at my friend, Jack’s apartment so often, that he leaves the key under the cactus outside the door.
Now this kind of thing is common knowledge. If someone is out on errands, expecting family home, the key is hidden in plain sight. (under the cactus or the doormat or something like that)
So someone can always look at these common places and gain entry and rob us blind. (Not that Jack has anything of value, except for old BoneyM records)
So Jack does something else everytime and tells only me about it. He’ll barricade the door with some sort of strong rope and hide the scissors someplace.
Or he’ll roll the heavy table outside to block the door (and the stairwell) knowing that I know how to unlock the castors and move the godaweful table.
Or he’ll put a facade of a door that looks like a safe, knowing I’ll peel it off later.
(Why can’t he just give me another key instead of making me do all this work? God only knows. He’s a lazy bum)

So a CSRF token is something similar. While your keys and session data might be stored on your computer and might be accessed by something foreign, it is not possible for them to steal your CSRF token, because it is short lived and changes frequently. This keeps malicious sites from doing … um … malicious things on your server.

The Resolution

Django, like Python, is batteries included.
So its Middleware includes CSRF protection.
In its various forms, to use in various places, it boils down to writing/including something like csrf_token

  • If I want to use it in a form, the default method is to just include <form method="post">{% csrf_token %} in any template that routes / forwards to another URL internally. (what do I do if I want to a URL externally? I don’t know yet. I’ll look stuff up later, if such stuff is even common. In my head, the threat model is for all my routes and urls and models on my server)
  • If I want to use it in an AJAX post, I have to remember to pass the CSRF token in as POST data with every POST request.

P.S. Subscribe to my mailing list!
Forward these posts and letters to your friends and get them to subscribe!
P.P.S. Feed my insatiable reading habit.