CSRF Protection in FastAPI
Blog post from StackHawk
Cross-Site Request Forgery (CSRF) is a common and easily executed attack method used in phishing and social engineering, where a user's browser unknowingly submits a request to a vulnerable site, which could range from transferring funds to liking a social media post. While CORS can prevent certain malicious scripts, it does not stop the submission of HTML forms, though the rise of Single-Page Web Apps using APIs has reduced the risk of CSRF. To protect FastAPI applications from CSRF attacks, the FastAPI CSRF Protect library offers a flexible solution inspired by `flask-wtf` and `fast-api-jwt-auth`, using expiring signed tokens transmitted via cookies or headers. The guide details the implementation steps, such as setting up the library, creating a CSRF token endpoint, and ensuring validation in request handlers, while also highlighting the need for diligence in securing endpoints due to the reliance on dependency injection. Written by Tim Armstrong, a seasoned engineer and technical writer, the post emphasizes the importance of thorough peer reviews in maintaining secure FastAPI applications.