Spring Boot Security Guide: HTTPS, CSRF, XSS, and Dependency Hardening

This comprehensive guide walks you through securing Spring Boot applications by configuring TLS, implementing Spring Security for authentication, CSRF, XSS and SQL injection defenses, hardening HTTP headers, scanning third‑party dependencies with OWASP Dependency‑Check, and applying best‑practice DevOps hardening steps for a defense‑in‑depth posture.

Ray's Galactic Tech
Ray's Galactic Tech
Ray's Galactic Tech
Spring Boot Security Guide: HTTPS, CSRF, XSS, and Dependency Hardening

Overview

The guide presents a defense‑in‑depth approach for securing Spring Boot applications, covering transport‑layer encryption, application‑layer protections (authentication, CSRF, XSS, SQL injection), dependency vulnerability scanning, and HTTP security‑header hardening.

1. Transport Layer Security (HTTPS)

Step 1 – Obtain a certificate

Production: use a CA‑signed certificate (e.g., Let’s Encrypt, DigiCert).

Testing: generate a self‑signed certificate.

keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.p12 -storetype PKCS12 -validity 365

Step 2 – Spring Boot configuration

server.port=8443
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=your-secret-password
server.ssl.key-alias=mydomain

Step 3 – Enforce HTTPS

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.requiresChannel(channel -> channel.anyRequest().requiresSecure());
    return http.build();
}

2. Application Layer Security – Spring Security

2.1 Authentication and Password Storage

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
// Example: user.setPassword(passwordEncoder.encode(rawPassword));

2.2 CSRF Protection

Enabled by default – Spring Security generates a CSRF token per session.

Thymeleaf forms automatically include the token.

For SPA APIs, read the token from cookie/header and send it in X‑CSRF‑TOKEN header.

Disabling CSRF (not recommended for stateful apps):

http.csrf(csrf -> csrf.disable());

2.3 XSS Mitigation

Input validation using JSR‑303 annotations (e.g., @NotBlank, @Email).

Sanitize rich‑text with Jsoup:

String safeHtml = Jsoup.clean(unsafeHtml, Whitelist.basicWithImages());

Output encoding – Thymeleaf’s th:text escapes HTML by default.

Content‑Security‑Policy (CSP) header for additional XSS defense:

http.headers(headers -> headers
    .addHeaderWriter(new StaticHeadersWriter("Content‑Security‑Policy",
        "default-src 'self'; script-src 'self' https://cdn.safe.com;")));

2.4 SQL Injection Prevention

Use parameterized queries with JPA/Hibernate/MyBatis.

@Query("SELECT u FROM User u WHERE u.username = :username")
User findByUsername(@Param("username") String username);
<select id="findUser" resultType="User">
    SELECT * FROM user WHERE username = #{username}
</select>
<!-- Never concatenate SQL with ${} -->

3. Dependency Security and Vulnerability Scanning

Integrate OWASP Dependency‑Check into Maven:

<plugin>
    <groupId>org.owasp</groupId>
    <artifactId>dependency-check-maven</artifactId>
    <version>8.2.1</version>
    <executions>
        <execution>
            <goals><goal>check</goal></goals>
        </execution>
    </executions>
</plugin>

Run the scan and update dependencies:

mvn verify
mvn dependency-check:check
mvn versions:display-dependency-updates

4. HTTP Security Header Configuration

http.headers(headers -> headers
    .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
    .httpStrictTransportSecurity(hsts -> hsts.includeSubDomains(true).maxAgeInSeconds(31536000))
    .frameOptions(frame -> frame.sameOrigin())
    .xssProtection(xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK))
    .contentTypeOptions(contentType -> {}));

Common security headers to enable:

HSTS – forces HTTPS.

X‑Frame‑Options – prevents click‑jacking.

X‑Content‑Type‑Options – disables MIME sniffing.

CSP – core XSS mitigation.

5. Defense‑in‑Depth Summary

Network layer: HTTPS, firewalls.

System layer: least‑privilege, regular patching.

Application layer: Spring Security, CSRF, XSS, SQL‑injection defenses.

Dependency layer: automated scanning, timely updates.

Operations layer: Actuator hardening, audit logging.

Before release, run penetration tests with tools such as OWASP ZAP or Burp Suite to uncover residual risks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Spring BootCSRFXSSHTTPSDependency-Check
Ray's Galactic Tech
Written by

Ray's Galactic Tech

Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.