Add support for csrf tokens in html forms with jinja #11658
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Now FastAPI with support for csrf tokens in html forms with jinja
Added some improvements for using CSRF tokens in HTML forms without affecting the current functionality of the middleware starlette-csrf. The improvement simplifies the process of obtaining the CSRF token by unifying the search logic into a single function _get_submitted_csrf_token. Now, the function will first attempt to obtain the token from the headers, and if it does not find it there, it will search for it in the form. Additionally, this new functionality addresses the crash issue that occurs in Starlette due to body consumption.
This is particularly useful for integration with FastAPI and the development of secure websites utilizing forms.
Now, all that's needed is to add the starlette_csrf middleware and utilize the following template processor in your FastAPI code:
Now, the middleware integrates with a context processor, a function that returns a dictionary containing the CSRF token, CSRF input, and CSRF header for use with other tools such as HTMX.
Simply using {{ csrf_input | safe }} in each form is now sufficient to ensure a more secure web application. For example:
Furthermore, we can use {{ csrf_header }} in HTMX requests. For example:
Feel free to let me know if you need further adjustments or improvements!