CSRF #236
-
I wasn't able to find anything on CSRF protection for blacksheep. Is there a solution other than rolling my own? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Hi @bitnom - that's a good question. I didn't work on built-in handling of CSRF Anti-Forgery tokens, yet, but it's one of the things I want to add. Since you are asking, I am willing to work on this as soon as I get a free moment, one of these days. I already have a partial implementation, so this is a low hanging fruit. |
Beta Was this translation helpful? Give feedback.
-
@bitnom With the solution I am proposing, the general idea is that it is sufficient to use a Jinja2 tag and to pass the web request to the template context, to have handling of anti-forgery tokens. Example: @app.router.get("/")
async def home(request):
home_model = {...}
return view("form_1", home_model, request=request)
@app.router.post("/user")
async def create_username():
# This function is called after validation of the Anti-Forgery token
# ...
return no_content() Jinja2 template (note the custom tag <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h1>{{heading}}</h1>
<p>{{paragraph}}</p>
<form action="/user" method="post">
{% af_input %}
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
</body>
</html> Tokens can be sent using form, or an header (for AJAX / fetch requests), and are validated by default for all "PATCH POST PUT DELETE" requests. Otherwise, it's also possible to use the middleware without Jinja2 - but this requires more work on the developer's side. Anti-forgery tokens validation won't be active by default. For example I haven't used Anti-Forgery validation since a long time because all web apps I build today use the HTML5 storage to store authentication JWTs, which are sent using I am also considering whether to include a decorator to support disabling anti-forgery validation when desired. |
Beta Was this translation helpful? Give feedback.
-
This is now available and documented https://www.neoteroi.dev/blacksheep/anti-request-forgery/ |
Beta Was this translation helpful? Give feedback.
Hi @bitnom - that's a good question. I didn't work on built-in handling of CSRF Anti-Forgery tokens, yet, but it's one of the things I want to add. Since you are asking, I am willing to work on this as soon as I get a free moment, one of these days. I already have a partial implementation, so this is a low hanging fruit.