Content Security Policy in Python — ELI5

Imagine you’re hosting a private party. You give the bouncer a guest list: “Only let in people from this list. Everyone else gets turned away at the door.”

That’s what a Content Security Policy (CSP) does for your website.

When someone visits your website, the page needs to load things — scripts that make buttons work, styles that make it pretty, images, fonts, and videos. Normally, the browser loads anything the page asks for, from anywhere on the internet. But that openness is a problem.

If a hacker manages to sneak a tiny piece of code into your page (maybe through a comment form or a broken plugin), the browser happily runs it. That malicious code could steal passwords, redirect users to fake sites, or spy on everything they type.

A Content Security Policy is your guest list. You tell the browser: “Only load scripts from my own server and from cdn.example.com. Reject scripts from everywhere else.” Even if a hacker injects code that tries to load something from evil-hackers.com, the browser checks the guest list, doesn’t find it, and blocks the attempt.

Python developers add this guest list as a special header that the server sends with every page. Django, Flask, and FastAPI all support it through middleware or extensions.

The beautiful part: even if your code has a bug that lets an attacker inject something, CSP acts as a safety net. The injected code tries to run or load something unauthorized, and the browser says “not on the list, not happening.”

The one thing to remember: A Content Security Policy is a guest list that tells the browser which scripts, styles, and resources are allowed — blocking anything a hacker tries to sneak in.

pythonsecurityweb

See Also