Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

When building a Spring web application, it’s important to focus on security. Cross-site scripting (XSS) is one of the most critical attacks on web security.

Preventing the XSS attack is a challenge in a Spring application. Spring provides built-in help for complete protection.

In this tutorial, we’ll use the available Spring Security features.

2. What Is a Cross-Site Scripting (XSS) Attack?

2.1. Definition of the Problem

XSS is a common type of injection attack. In XSS, the attacker tries to execute malicious code in a web application. They interact with it through a web browser or HTTP client tools like Postman.

There are two types of XSS attacks:

  • Reflected or Nonpersistent XSS
  • Stored or Persistent XSS

In Reflected or Nonpersistent XSS, untrusted user data is submitted to a web application, which is immediately returned in the response, adding untrustworthy content to the page. The web browser assumes the code came from the web server and executes it. This might allow a hacker to send you a link that, when followed, causes your browser to retrieve your private data from a site you use and then make your browser forward it to the hacker’s server.

In Stored or Persistent XSS, the attacker’s input is stored by the webserver. Subsequently, any future visitors may execute that malicious code.

2.2. Defending Against the Attack

The main strategy for preventing XSS attacks is to clean user input.

In a Spring web application, the user’s input is an HTTP request. To prevent the attack, we should check the HTTP request’s content and remove anything that might be executable by the server or in the browser.

For a regular web application, accessed through a web browser, we can use Spring Security‘s built-in features (Reflected XSS).

3. Making an Application XSS Safe with Spring Security

Spring Security provides several security headers by default. It includes the X-XSS-Protection header. X-XSS-Protection tells the browser to block what looks like XSS. Spring Security can automatically add this security header to the response. To activate this, we configure the XSS support in the Spring Security configuration class.

Using this feature, the browser does not render when it detects an XSS attempt. However, some web browsers haven’t implemented the XSS auditor. In this case, they don’t make use of the X-XSS-Protection header. To overcome this issue, we can also use the Content Security Policy (CSP) feature.

The CSP is an added layer of security that helps mitigate XSS and data injection attacks. To enable it, we need to configure our application to return a Content-Security-Policy header by providing a SecurityFilterChain bean:

@Configuration
public class SecurityConf {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.headers(headers ->
                headers.xssProtection(
                        xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK)
                ).contentSecurityPolicy(
                        cps -> cps.policyDirectives("script-src 'self'")
                ));
        return http.build();
    }
}

4. Conclusion

In this article, we saw how to prevent XSS attacks by using Spring Security’s xssProtection feature.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW