Reputation: 450
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.
Upvotes: 1
Views: 4515
Reputation: 799
As Stephen P mentions, you should generally be encoding data on output. You want to do this on output to ensure you're using the correct encoding for the output, and to prevent double encoding. The OWASP encoders are a good choice for this. See the OWASP XSS Prevention Cheat Sheet for details on when to use various encoders.
You want to validate/sanitize on input as much as possible, using white list validation if possible. But for free form text you won't, and shouldn't, do XSS encoding at this point.
Upvotes: 1