Menu
CoddyTech

CSRF and APIs

Part of the JSON APIs section of Coddy's Django journey. Lesson 6 of 19.

A real program that sends POST /api/tasks/ gets 403 Forbidden. Django's CSRF protection wants every POST to carry a secret token from one of your own pages, so another website cannot make a visitor's browser submit your forms. A program has no such page and no token.

@csrf_exempt, from django.views.decorators.csrf, turns the check off for one view:

@csrf_exempt
def webhook(request):
    ...

That gives something up: any website can now make a visitor's browser send this POST. It is fine for a view that does not depend on who is logged in, like the task list. An API that acts as the logged-in user keeps CSRF on, and its page's script sends the token in an X-CSRFToken header.

challenge icon

Challenge

Medium

Let programs without a CSRF token create tasks:

  • POST /api/tasks/ works with no token.
  • Only task_list is exempt.

Press Run, then type this in the Shell tab. Before the change it prints 403, after it 201: from django.test import Client; print(Client(enforce_csrf_checks=True).post("/api/tasks/", {"title": "Pay rent"}, content_type="application/json").status_code)

Try it yourself

import json

from django.http import JsonResponse
from django.shortcuts import render

from .models import Task


def task_to_dict(task):
    return {
        "id": task.id,
        "title": task.title,
        "done": task.done,
        "priority": task.priority,
    }


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})


def stats(request):
    data = {
        "total": Task.objects.count(),
        "done": Task.objects.filter(done=True).count(),
    }
    return JsonResponse(data)


def task_list(request):
    if request.method == "POST":
        data = json.loads(request.body)
        task = Task.objects.create(
            title=data["title"],
            priority=data.get("priority", "normal"),
        )
        return JsonResponse(task_to_dict(task), status=201)
    tasks = Task.objects.all()
    done = request.GET.get("done")
    if done == "true":
        tasks = tasks.filter(done=True)
    elif done == "false":
        tasks = tasks.filter(done=False)
    return JsonResponse([task_to_dict(task) for task in tasks], safe=False)


def task_detail(request, pk):
    task = Task.objects.filter(pk=pk).first()
    if task is None:
        return JsonResponse({"error": "Task not found"}, status=404)
    return JsonResponse(task_to_dict(task))

All lessons in JSON APIs

Practice on your own: Django playground