DEV Community

eidher
eidher

Posted on • Edited on

3 3

Handling Cross-Site Scripting (XSS) in Java

Cross-site scripting (XSS) is a type of security vulnerability in web applications where an attacker injects malicious scripts through some kind of user input (like input boxes, URL parameters, HTML headers, etc)
It is important to prevent XSS attacks to safeguard the confidentiality, integrity, and availability of the information of the web application. The two main cross-site scripting flaws are reflected and stored:

Reflected XSS

Malicious content from a user request is displayed to the user or it is written into the page after from server response. For instance, in the next screenshot, the credit card number field is vulnerable. After the number, there is a script to be injected:



<script>alert('my javascript here')</script>


Enter fullscreen mode Exit fullscreen mode

Alt Text
When the purchase button is clicked, the alert windows is displayed:
Alt Text

A patch to the flaw in Java

When you have a String RequestParam, avoid handling it without sanitization:
Alt Text

The OWASP Java encoder has a method called forHtml for that purpose:
Alt Text

Now, the field is printed as text, but it is not executed:
Alt Text

Stored XSS

The payload is persisted. For example, in the next screenshot, you can see that a script is added as a comment. When the page is loaded the script is executed and printed as part of the code.
Alt Text

A patch to the flaw in Java

The solution is to sanitize the RequestBody before handling it:

Alt Text

Now, the comment is printed as text, but it is not executed:
Alt Text

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay