How to prevent from Cross Site Scripting (XSS) attack in Spring Boot application?

Viewed 8738

I want to secure my spring boot app with XSS protection. I have Spring Boot application implemented with Spring Security.

Additionally I have second application (frontend) working on different port (different origin) - that is why I cannot set Content Security Policy as 'self' for preventing XSS attacks.

How can I implement basic XSS protection, filter that can remove all suspicious strings from incoming requests?

Edit:

I have found this article: https://www.baeldung.com/spring-prevent-xss. But this project uses ESAPI library wchich is pretty big and slowing down application, so I would like to find different, easier approach.

1 Answers

Universal filters can be unreliable. It's usually better to apply validation for inputs, and encoding for outputs individually, as what's valid and what encoding is needed depends on the value and its context.

The main thing to do is apply the correct encoding where necessary and be careful where values are used. See the OWASP XSS Prevention page.

The Baeldung article uses ESAPI.encoder().canonicalize(value) which decodes various sequences beginning with &, % or \.

If these are valid characters in any of your inputs, then decoding can corrupt the input and shouldn't be done.

If they're not valid, then the input should be rejected. If the input really was malicious, then you shouldn't be processing it anyway. So the call to ESAPI might as well be:

if(value.matches(".*[\\\\%&].*")) {
    throw new RuntimeException("Invalid character");
}
Related