How can we prevent html injection in FastAPI?
Asked Answered
D

1

8

We are developing REST APIs using python framework called FastAPI. The code security test failed for html injection. They are sending some html tag code in the post payload, we are inserting that in DB and sending same in GET Response. Is there any way to prevent this HTML injection while processing request in FastAPI.

Dalessio answered 19/8, 2020 at 13:39 Comment(2)
You could use base64 encodeBuprestid
base64 encode will resolve nothing - unless you are presenting back encoded content in an HTML document, which is basically useless if one was expecting readable text. Upon decoding, the HTML control characters and tags would be "reconstructed" and the injection would take place just the same.Comus
C
8

yes. No framework is going to magically change the content you get without you being explicit about it. (Imagine if it was a REST API for recording HTML snippets from an internal system to be used in rendering web pages in another endpoint: you'd need the HTML as is)

It is just a matter of calling a escape function on your input data, before putting that on the db.

Python's standard library html.escape function suffices in this case.

There is no code in your question, and I don't know FASTAPI by heart - but if it puts the payload in the DB without going through any code you write, then you should either customize that and put in this call to preprocess your data, or add a triggered stage (that is, an event subscriber) that will do that for you.

Comus answered 19/8, 2020 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.