I have an API written in Java where I am doing POST call but the malicious content is being sent to the API. Ideally, to prevent XSS attack, the API should not accept such data or at least sanitize it before storing/responding to it.
{"first_name":"<script>alert(document.cookie);</script>","last_name":"
<script>alert(document.cookie);</script>"}
I want to add XSS validations/ sanitize script tags in Java to prevent the content from XSS attack. Can anyone suggest the best way to prevent XSS attack in Java? Is there a way to encode and decode the HTML tags shown above?
After going through the different documentation, I found that owasp-java-encoder can be used to encode HTML content and this function can be used to encode HTML Content Context.
<%= Encode.forHtmlContent(UNTRUSTED) %>
I am looking for something which allows me to encode the HTML content while storing data and decode it while displaying it.
<script>...</script>it is perfectly safe to store that. If you're then going to send that to a web page then you need to sanitize it. But what if you're also going to output that to a PDF? I don't want it to appear as<script> ...so it should not be sanitized -- but too late! you've already stored the sanitized version, which can't be safely reversed. - Stephen P