# FastAPI CSRF Protect
[![Build Status](https://travis-ci.com/aekasitt/fastapi-csrf-protect.svg?branch=master)](https://app.travis-ci.com/github/aekasitt/fastapi-csrf-protect)
[![Package Vesion](https://img.shields.io/pypi/v/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)
[![Format](https://img.shields.io/pypi/format/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)
[![Python Version](https://img.shields.io/pypi/pyversions/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)
[![License](https://img.shields.io/pypi/l/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)
## Features
FastAPI extension that provides stateless Cross-Site Request Forgery (XSRF) Protection support.
Aimed to be easy to use and lightweight, we adopt [Double Submit Cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie) mitigation pattern.
If you were familiar with `flask-wtf` library this extension suitable for you.
This extension inspired by `fastapi-jwt-auth` 😀
- Storing `fastapi-csrf-token` in cookies or serve it in template's context
## Installation
The easiest way to start working with this extension with pip
```bash
pip install fastapi-csrf-protect
# or
poetry add fastapi-csrf-protect
```
## Getting Started
The following examples show you how to integrate this extension to a FastAPI App
### Example Login Form
```python
from fastapi import FastAPI, Request, Depends
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi_csrf_protect import CsrfProtect
from fastapi_csrf_protect.exceptions import CsrfProtectError
from pydantic import BaseModel
app = FastAPI()
templates = Jinja2Templates(directory="templates")
class CsrfSettings(BaseModel):
secret_key: str = "asecrettoeverybody"
cookie_samesite: str = "none"
@CsrfProtect.load_config
def get_csrf_config():
return CsrfSettings()
@app.get("/login")
def form(request: Request, csrf_protect: CsrfProtect = Depends()):
"""
Returns form template.
"""
csrf_token, signed_token = csrf_protect.generate_csrf_tokens()
response = templates.TemplateResponse(
"form.html", {"request": request, "csrf_token": csrf_token}
)
csrf_protect.set_csrf_cookie(signed_token, response)
return response
@app.post("/login", response_class=JSONResponse)
async def create_post(request: Request, csrf_protect: CsrfProtect = Depends()):
"""
Creates a new Post
"""
await csrf_protect.validate_csrf(request)
response: JSONResponse = JSONResponse(status_code=200, content={"detail": "OK"})
csrf_protect.unset_csrf_cookie(response) # prevent token reuse
return response
@app.exception_handler(CsrfProtectError)
def csrf_protect_exception_handler(request: Request, exc: CsrfProtectError):
return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})
```
## Contributions
To contribute to the project, fork the repository and clone to your local device and install preferred testing dependency [pytest](https://github.com/pytest-dev/pytest)
Alternatively, run the following command on your terminal to do so:
```bash
pip install -U poetry
poetry install
```
Testing can be done by the following command post-installation:
```bash
poetry install --with test
pytest
```
## Changelog
### 🚧 Breaking Changes (0.3.0 -> 0.3.1) The double submit update
* The `generate_csrf` method has now been marked for deprecation
* The recommended method is now `generate_csrf_tokens` which returns a tuple of tokens, first unsigned
and the latter signed
* Recommended pattern is for the first token is aimed for returning as part of context
* Recommended pattern is for the signed token to be set in client's cookie completing [Double Submit Cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie)
* To prevent token reuse, protected endpoint can unset the signed CSRF Token in client's cookies as
per example code and recommended pattern.
### 🚧 Breaking Changes (0.3.1 -> 0.3.2) The anti-JavaScript update
* New keys are added at setup `token_location` (either `body` or `header`) and `token_key` is key
where form-encoded keeps the csrf token stored, cross-checked with csrf secret in cookies.
* Asynchronous `validate_csrf` method now needs to be awaited therefore protected endpoints need to
be asynchronous as well.
### Run Examples
To run the provided examples, first you must install extra dependencies [uvicorn](https://github.com/encode/uvicorn) and [jinja2](https://github.com/pallets/jinja/)
Alternatively, run the following command on your terminal to do so
```bash
poetry install --with examples
```
Running the example utilizing form submission
```bash
uvicorn examples.body:app
```
Running the example utilizing headers via JavaScript
```bash
uvicorn examples.header:app
```
## License
This project is licensed under the terms of the MIT license.
Raw data
{
"_id": null,
"home_page": "https://github.com/aekasitt/fastapi-csrf-protect",
"name": "fastapi-csrf-protect",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.7,<4.0",
"maintainer_email": "",
"keywords": "starlette,fastapi,csrf,xsrf,cross-site request forgery,samesite,asynchronous",
"author": "Sitt Guruvanich",
"author_email": "aekazitt@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/f3/74/611bf8ed4e2a43b95c75fe34d16caadecd0959a52e87499de430adebdca6/fastapi_csrf_protect-0.3.3.tar.gz",
"platform": null,
"description": "# FastAPI CSRF Protect\n\n[![Build Status](https://travis-ci.com/aekasitt/fastapi-csrf-protect.svg?branch=master)](https://app.travis-ci.com/github/aekasitt/fastapi-csrf-protect)\n[![Package Vesion](https://img.shields.io/pypi/v/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)\n[![Format](https://img.shields.io/pypi/format/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)\n[![Python Version](https://img.shields.io/pypi/pyversions/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)\n[![License](https://img.shields.io/pypi/l/fastapi-csrf-protect)](https://pypi.org/project/fastapi-csrf-protect)\n\n## Features\n\nFastAPI extension that provides stateless Cross-Site Request Forgery (XSRF) Protection support.\nAimed to be easy to use and lightweight, we adopt [Double Submit Cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie) mitigation pattern.\nIf you were familiar with `flask-wtf` library this extension suitable for you.\nThis extension inspired by `fastapi-jwt-auth` \ud83d\ude00\n\n- Storing `fastapi-csrf-token` in cookies or serve it in template's context\n\n## Installation\n\nThe easiest way to start working with this extension with pip\n\n```bash\npip install fastapi-csrf-protect\n# or\npoetry add fastapi-csrf-protect\n```\n\n## Getting Started\n\nThe following examples show you how to integrate this extension to a FastAPI App\n\n### Example Login Form\n\n```python\nfrom fastapi import FastAPI, Request, Depends\nfrom fastapi.responses import JSONResponse\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi_csrf_protect import CsrfProtect\nfrom fastapi_csrf_protect.exceptions import CsrfProtectError\nfrom pydantic import BaseModel\n\napp = FastAPI()\ntemplates = Jinja2Templates(directory=\"templates\")\n\nclass CsrfSettings(BaseModel):\n secret_key: str = \"asecrettoeverybody\"\n cookie_samesite: str = \"none\"\n\n@CsrfProtect.load_config\ndef get_csrf_config():\n return CsrfSettings()\n\n@app.get(\"/login\")\ndef form(request: Request, csrf_protect: CsrfProtect = Depends()):\n \"\"\"\n Returns form template.\n \"\"\"\n csrf_token, signed_token = csrf_protect.generate_csrf_tokens()\n response = templates.TemplateResponse(\n \"form.html\", {\"request\": request, \"csrf_token\": csrf_token}\n )\n csrf_protect.set_csrf_cookie(signed_token, response)\n return response\n\n@app.post(\"/login\", response_class=JSONResponse)\nasync def create_post(request: Request, csrf_protect: CsrfProtect = Depends()):\n \"\"\"\n Creates a new Post\n \"\"\"\n await csrf_protect.validate_csrf(request)\n response: JSONResponse = JSONResponse(status_code=200, content={\"detail\": \"OK\"})\n csrf_protect.unset_csrf_cookie(response) # prevent token reuse\n return response\n\n@app.exception_handler(CsrfProtectError)\ndef csrf_protect_exception_handler(request: Request, exc: CsrfProtectError):\n return JSONResponse(status_code=exc.status_code, content={\"detail\": exc.message})\n\n```\n\n## Contributions\n\nTo contribute to the project, fork the repository and clone to your local device and install preferred testing dependency [pytest](https://github.com/pytest-dev/pytest)\nAlternatively, run the following command on your terminal to do so:\n\n```bash\npip install -U poetry\npoetry install\n```\n\nTesting can be done by the following command post-installation:\n\n```bash\npoetry install --with test\npytest\n```\n\n## Changelog\n\n### \ud83d\udea7 Breaking Changes (0.3.0 -> 0.3.1) The double submit update\n\n* The `generate_csrf` method has now been marked for deprecation\n* The recommended method is now `generate_csrf_tokens` which returns a tuple of tokens, first unsigned\n and the latter signed\n* Recommended pattern is for the first token is aimed for returning as part of context\n* Recommended pattern is for the signed token to be set in client's cookie completing [Double Submit Cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie)\n* To prevent token reuse, protected endpoint can unset the signed CSRF Token in client's cookies as\n per example code and recommended pattern.\n\n### \ud83d\udea7 Breaking Changes (0.3.1 -> 0.3.2) The anti-JavaScript update\n\n* New keys are added at setup `token_location` (either `body` or `header`) and `token_key` is key\n where form-encoded keeps the csrf token stored, cross-checked with csrf secret in cookies.\n* Asynchronous `validate_csrf` method now needs to be awaited therefore protected endpoints need to\n be asynchronous as well.\n\n### Run Examples\n\nTo run the provided examples, first you must install extra dependencies [uvicorn](https://github.com/encode/uvicorn) and [jinja2](https://github.com/pallets/jinja/)\nAlternatively, run the following command on your terminal to do so\n\n```bash\npoetry install --with examples\n```\n\nRunning the example utilizing form submission\n\n```bash\nuvicorn examples.body:app\n```\n\nRunning the example utilizing headers via JavaScript\n\n```bash\nuvicorn examples.header:app\n```\n\n## License\n\nThis project is licensed under the terms of the MIT license.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Stateless implementation of Cross-Site Request Forgery (XSRF) Protection by using Double Submit Cookie mitigation pattern",
"version": "0.3.3",
"project_urls": {
"Homepage": "https://github.com/aekasitt/fastapi-csrf-protect",
"Repository": "https://github.com/aekasitt/fastapi-csrf-protect"
},
"split_keywords": [
"starlette",
"fastapi",
"csrf",
"xsrf",
"cross-site request forgery",
"samesite",
"asynchronous"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "d87f8794338210788600b1d8fdd236cee3db03ae901d08031634c166afc2e87c",
"md5": "c0085fcd8aa9f61da584ea41c6601e4b",
"sha256": "6145de11d592c7e8c167dbf7bd7d0656b2da272dabe87bd98b694e590001f264"
},
"downloads": -1,
"filename": "fastapi_csrf_protect-0.3.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c0085fcd8aa9f61da584ea41c6601e4b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7,<4.0",
"size": 9667,
"upload_time": "2023-11-21T04:58:24",
"upload_time_iso_8601": "2023-11-21T04:58:24.304915Z",
"url": "https://files.pythonhosted.org/packages/d8/7f/8794338210788600b1d8fdd236cee3db03ae901d08031634c166afc2e87c/fastapi_csrf_protect-0.3.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "f374611bf8ed4e2a43b95c75fe34d16caadecd0959a52e87499de430adebdca6",
"md5": "5665120e10410549506b48539fae18d7",
"sha256": "c946288cca22b0d8c65c7252030f3e931ee2f9c24a621bbb4bc56c29c729a938"
},
"downloads": -1,
"filename": "fastapi_csrf_protect-0.3.3.tar.gz",
"has_sig": false,
"md5_digest": "5665120e10410549506b48539fae18d7",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7,<4.0",
"size": 8946,
"upload_time": "2023-11-21T04:58:27",
"upload_time_iso_8601": "2023-11-21T04:58:27.641065Z",
"url": "https://files.pythonhosted.org/packages/f3/74/611bf8ed4e2a43b95c75fe34d16caadecd0959a52e87499de430adebdca6/fastapi_csrf_protect-0.3.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-11-21 04:58:27",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "aekasitt",
"github_project": "fastapi-csrf-protect",
"travis_ci": true,
"coveralls": false,
"github_actions": false,
"lcname": "fastapi-csrf-protect"
}