FastAPI is an unopinionated framework, meaning it doesn't include built-in CSRF (Cross-Site Request Forgery) protection. This guide outlines a robust, stateless, and flexible strategy to secure your application for all types of clients.
Our approach will be to use the Double Submit Cookie Pattern for browser-based clients and Token-Based Authentication for non-browser clients, using a single "smart" dependency to differentiate between them.
- For Browser Users (Forms & AJAX):
- The server generates a CSRF token and sets it in a cookie.