Vulnerability Testing — Simple Explanation with Real World Examples
Understand SQL Injection, XSS, CSRF, and Security Headers with easy explanations and simple code examples to protect your web applications.
🧠 Vulnerability Testing
Learn how to find and fix common web application vulnerabilities with simple examples.
🔍 What is Vulnerability Testing?
Vulnerability testing is the process of finding weak points in your web app before hackers do.
It helps make sure your:
- Database is safe
- User data is protected
- Web pages cannot be misused
We’ll learn four major vulnerabilities that most web apps face and how to prevent them with simple logic and code.
💉 1. SQL Injection (SQLi)
Problem:
SQL Injection happens when attackers put malicious SQL code inside input fields to access data from your database.
🔸 Example of an Attack
Let’s say your backend code looks like this:
username = input("Enter username: ")
query = f"SELECT * FROM users WHERE name = '{username}'"
db.execute(query)If a user types this:
admin' OR '1'='1Then the query becomes:
SELECT * FROM users WHERE name = 'admin' OR '1'='1';This means the attacker can log in as anyone — even without a password!
✅ How to Prevent It
Solution: Use parameterized queries or ORM models.
Example (Python + SQLAlchemy):
db.execute("SELECT * FROM users WHERE name = :name", {"name": username})Or using ORM safely:
user = db.query(User).filter(User.name == username).first()💡 Real-World Example: A shopping app could be hacked if the product search field is not protected. Attackers could use SQL injection to see all customer details or change prices.
🧨 2. Cross-Site Scripting (XSS)
Problem: XSS happens when attackers inject malicious JavaScript code into your website, which then runs in other users’ browsers.
🔸 Example of an Attack
If your website shows user comments directly like this:
<p>User says: <%= comment %></p>An attacker can post:
<script>alert('You got hacked!')</script>Then, every user who views that page will see a popup — or worse, the attacker could steal their cookies.
✅ How to Prevent It
Simple Rules:
- Sanitize user inputs (remove script tags).
- Escape HTML before rendering it.
- Use frameworks (like React or Vue) that do this automatically.
- Add a Content Security Policy (CSP).
Example (HTML Safe Output):
<p>User says: <script>alert('You got hacked!')</script></p>Now the code shows as text — not as a running script.
💡 Real-World Example: In 2019, eBay had an XSS bug that let hackers steal user data by inserting JavaScript into product descriptions. Escaping user input is now a must for all big websites.
🔒 3. CSRF (Cross-Site Request Forgery)
Problem: CSRF tricks users into performing actions they didn’t intend — like sending money or changing passwords.
🔸 Example of an Attack
Imagine you are logged in to your bank, and someone sends you this hidden form:
<form action="https://bank.com/transfer" method="POST">
<input type="hidden" name="to" value="attacker">
<input type="hidden" name="amount" value="10000">
</form>If you open this page, it will automatically submit the form, transferring money from your account.
✅ How to Prevent It
Solution:
- Use CSRF tokens (unique per request).
- Validate the token on the server.
- Use SameSite cookies.
Example (FastAPI Pseudo Code):
@app.post("/transfer")
def transfer(request: Request):
csrf_token = request.headers.get("X-CSRF-Token")
if csrf_token != "expected_token":
raise HTTPException(status_code=403, detail="Invalid CSRF token")💡 Real-World Example: In 2008, MySpace had a CSRF issue that automatically made users “friend” a hacker’s account when they viewed a page. Now most frameworks (like Django, Laravel, Flask) add CSRF protection automatically.
🛡️ 4. Security Headers
Problem: Even with secure code, browsers need rules about what content they can load. Security headers tell browsers how to behave safely.
🔸 Common Security Headers
| Header | What it Does | Example |
|---|---|---|
| Content-Security-Policy (CSP) | Limits where scripts and data can come from | default-src 'self' |
| X-Frame-Options | Stops your page from being shown in iframes | DENY |
| X-Content-Type-Options | Prevents MIME type attacks | nosniff |
| Strict-Transport-Security (HSTS) | Forces HTTPS | max-age=31536000; includeSubDomains |
| Referrer-Policy | Hides user’s referrer info | no-referrer |
✅ Example: Add Security Headers in FastAPI
from fastapi import FastAPI, Response
app = FastAPI()
@app.middleware("http")
async def add_security_headers(request, call_next):
response: Response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Content-Security-Policy"] = "default-src 'self'"
return response💡 Real-World Example: Banking sites and payment gateways always set these headers to stop their pages from being opened inside fake sites or phishing pages.
🧾 Summary
| Vulnerability | Problem | Solution |
|---|---|---|
| SQL Injection | Attackers inject SQL commands | Use parameterized queries or ORM |
| XSS | Injects malicious JavaScript | Sanitize and escape input |
| CSRF | Forces unwanted user actions | Add CSRF tokens |
| Security Headers | Browser misbehavior | Set headers like CSP, HSTS, and X-Frame-Options |
💡 Real-World Understanding
Think of security like building locks for your house:
- SQL Injection → Prevents thieves from breaking your doors.
- XSS → Stops strangers from planting traps inside.
- CSRF → Blocks people from tricking you into opening doors for them.
- Security Headers → Are like guards who enforce house rules.
Vulnerability testing helps you test all these locks before the bad guys do. That’s why companies like Google, Amazon, and PayPal run daily vulnerability scans and regular penetration tests.