-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/")
def post_root():
with open("some_data", 'w') as f:
f.write("superimportant_data")DescriptionNow we have plugin fastapi_csrf_protect, but it looks like strange. Just see code here: https://www.stackhawk.com/blog/csrf-protection-in-fastapi/ Wanted SolutionFeature request for built-in csrf settings, which will looks like cors - as middleware. Just something like https://github.com/frankie567/starlette-csrf, but built-in fastapi Wanted Codefrom fastapi import FastAPI
from fastapi.middlewares import CSRFMiddleware
from app.core import app_config
app = FastAPI()
app.add_middleware(CSRFMiddleware, secret="__CHANGE_ME__")
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/", csrf_token=True) # by default
def post_root():
with open("secure_file", 'w') as f:
f.write("superimportant_data")
@app.post("/access_post_without_csrf/", csrf_token=False)
with open("unsecure_file", 'w') as f:
f.write("some_data")Alternativeshttps://github.com/frankie567/starlette-csrf Operating SystemLinux, Windows, macOS Operating System DetailsNo response FastAPI Versionlatest Python Version3.10.1 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
|
See: https://github.com/gnat/csrf-starlette-fastapi#why-you-may-not-need-a-csrf-middleware-in-2022 |
Beta Was this translation helpful? Give feedback.
-
It's good, that you have your own implementation. But I said about built-in support. How it's important we can see in similar issue in starlette, which now is discussion. |
Beta Was this translation helpful? Give feedback.
-
|
+1. This will be a really good enhancement for the framework |
Beta Was this translation helpful? Give feedback.
-
|
Update- why you don't need a middleware for CSRF in 2022: https://github.com/gnat/csrf-starlette-fastapi#why-you-may-not-need-a-csrf-middleware-in-2022 tl;dr: Browsers have improved enough that you can use a dual-cookie system: one lax, one strict. |
Beta Was this translation helpful? Give feedback.
-
|
@gnat it's okay for newer browsers. What about older? Also, not protected with subdomain attack |
Beta Was this translation helpful? Give feedback.
-
Why can't one just use the starlette middleware? |
Beta Was this translation helpful? Give feedback.
Update- why you don't need a middleware for CSRF in 2022: https://github.com/gnat/csrf-starlette-fastapi#why-you-may-not-need-a-csrf-middleware-in-2022
tl;dr: Browsers have improved enough that you can use a dual-cookie system: one lax, one strict.