Skip to main content
Web MobileAdvanced16 min readUpdated March 2025

Web Security Essentials

Protect your applications from the most common attacks: XSS, CSRF, SQL injection and insecure authentication. Includes safe patterns in JavaScript and Python.

Never Trust Input

Every value from a user, URL, header or third-party API is untrusted. Validate its shape on the server, escape it when displaying, and use parameterized queries when storing it.

Cross-Site Scripting (XSS)

XSS happens when attacker-supplied script is rendered as HTML. Insert text with `textContent`, rely on your framework's automatic escaping, and sanitize any HTML you must allow.

javascript
// Unsafe: attacker controls "comment"
element.innerHTML = comment;

// Safe: treated as plain text
element.textContent = comment;

// React escapes by default; avoid dangerouslySetInnerHTML
// unless the HTML is sanitized first.

SQL Injection

Never build queries by concatenating strings. Use parameterized queries so the database treats input strictly as data:

python
import sqlite3

conn = sqlite3.connect("app.db")
email = input("Email: ")

# Vulnerable: ' OR '1'='1 would return every user
# conn.execute(f"SELECT * FROM users WHERE email = '{email}'")

# Safe: parameter binding
row = conn.execute(
    "SELECT id, name FROM users WHERE email = ?", (email,)
).fetchone()
print(row)

Secure Password Storage

Never store plain-text passwords or fast hashes like MD5. Use a slow, salted algorithm such as bcrypt or Argon2:

python
import bcrypt

password = b"correct horse battery staple"

hashed = bcrypt.hashpw(password, bcrypt.gensalt(rounds=12))

# Later, at login
if bcrypt.checkpw(password, hashed):
    print("Login OK")

Security Checklist

Apply these defaults to every production site:

  • Serve everything over HTTPS and set HSTS.
  • Use `HttpOnly`, `Secure` and `SameSite` cookies for sessions.
  • Protect state-changing requests from CSRF with tokens or SameSite cookies.
  • Set a Content-Security-Policy to limit where scripts can load from.
  • Rate-limit login and API endpoints.
  • Keep dependencies updated and scan them for known vulnerabilities.

Key Takeaways

  • Treat all external input as untrusted and validate it on the server.
  • Use textContent, framework escaping and sanitization to prevent XSS.
  • Parameterized queries stop SQL injection.
  • Hash passwords with bcrypt or Argon2 and use secure cookie settings.

Contact Us

Have a question or feedback? Fill out the form below or reach us directly at support@nvaitraining.com