DEV Community

Rizwan Saleem
Rizwan Saleem

Posted on

How to secure your web application — a practical guide for developers

How to secure your web application — a practical guide for developers

Focused web application security is about reducing attack surface, validating trust boundaries, and assuming all external input is hostile. The OWASP Top Ten provides a practical map of the most common risks. This guide walks through the core vulnerabilities-XSS, CSRF, SQL injection, authentication and authorization flaws-and shows how to prevent them using modern patterns like secure headers, HTTPS, CSP, cookies, dependency scanning, and input validation.

Understanding the OWASP Top Ten

The OWASP Top Ten highlights categories such as broken access control, cryptographic failures, injection, insecure design, and security misconfiguration. Rather than memorizing the list, treat it as a checklist of failure modes:

  • Input is not validated or encoded.
  • Identity is not strongly verified.
  • Permissions are not enforced server-side.
  • Secrets and data are exposed in transit or at rest.
  • Dependencies introduce known vulnerabilities.

A secure application addresses all of these systematically.

Cross-Site Scripting (XSS)

XSS occurs when untrusted input is rendered in a browser without proper escaping, allowing attackers to run scripts.

Prevention strategies:

  • Output encoding: Escape data based on context (HTML, attribute, JavaScript, URL).
  • Use frameworks that auto-escape templates (React, Angular, Vue).
  • Avoid innerHTML; prefer safe DOM APIs like textContent.
  • Implement Content Security Policy (CSP) to block inline scripts.

Example:
Instead of:

element.innerHTML = userInput;
Enter fullscreen mode Exit fullscreen mode

Use:

element.textContent = userInput;
Enter fullscreen mode Exit fullscreen mode

Cross-Site Request Forgery (CSRF)

CSRF tricks authenticated users into submitting unwanted requests.

Prevention strategies:

  • CSRF tokens: Unique, unpredictable tokens per session or request.
  • SameSite cookies: Set cookies to SameSite=Lax or Strict.
  • Require re-authentication for sensitive actions.
  • Validate origin and referer headers where appropriate.

Example:
A form includes a hidden CSRF token that must match the server-side session value before processing.

SQL Injection

SQL injection allows attackers to manipulate queries by injecting malicious input.

Prevention strategies:

  • Use parameterized queries (prepared statements).
  • Avoid dynamic query construction with string concatenation.
  • Use ORM libraries that enforce query safety.
  • Apply least-privilege database access.

Example (safe query):

cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
Enter fullscreen mode Exit fullscreen mode

Authentication and Authorization

Authentication verifies identity; authorization determines access rights. Weaknesses here often lead to account takeover or privilege escalation.

Best practices:

  • Use strong password hashing (bcrypt, Argon2).
  • Implement multi-factor authentication (MFA).
  • Use secure session management (rotate session IDs, short expiry).
  • Enforce authorization checks on every request (never trust client-side checks).
  • Follow the principle of least privilege.

Common mistake:
Checking user roles only in frontend code instead of server-side validation.

HTTPS and Transport Security

All communication should be encrypted.

Key practices:

  • Enforce HTTPS using redirects and HSTS (HTTP Strict Transport Security).
  • Disable weak TLS versions and ciphers.
  • Use secure certificates and automate renewal (e.g., Let’s Encrypt).

Example header:

Strict-Transport-Security: max-age=31536000; includeSubDomains
Enter fullscreen mode Exit fullscreen mode

Security Headers

Security headers instruct browsers to enforce protections.

Important headers:

  • Content-Security-Policy: Restricts resource loading and script execution.
  • X-Content-Type-Options: Prevents MIME sniffing.
  • X-Frame-Options: Protects against clickjacking.
  • Referrer-Policy: Controls referrer data exposure.

Example CSP:

Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com
Enter fullscreen mode Exit fullscreen mode

Secure Cookie Configuration

Cookies often store session identifiers and must be protected.

Best practices:

  • HttpOnly: Prevent JavaScript access.
  • Secure: Send only over HTTPS.
  • SameSite: Mitigate CSRF.

Example:

Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Lax
Enter fullscreen mode Exit fullscreen mode

Dependency Scanning

Third-party libraries can introduce vulnerabilities.

Approach:

  • Use automated tools (Dependabot, Snyk, npm audit).
  • Keep dependencies updated.
  • Remove unused packages.
  • Monitor CVEs affecting your stack.

Example:
A project using an outdated version of a library with a known remote code execution vulnerability can be exploited even if your code is secure.

Input Validation

Input validation is your first line of defense.

Principles:

  • Validate on both client and server sides.
  • Use allow-lists rather than block-lists.
  • Enforce type, length, and format constraints.
  • Normalize input before validation.

Example:
For an email field:

  • Check format using regex.
  • Limit length.
  • Reject unexpected characters.

    Real-World Security Patterns

  • Defense in depth: Combine multiple controls (e.g., CSP + output encoding).

  • Zero trust: Treat every request as untrusted, even internal ones.

  • Fail securely: Default to denying access on error.

  • Logging and monitoring: Detect anomalies and attacks early.

  • Rate limiting: Prevent brute-force and abuse.

Illustration:
A login endpoint might include rate limiting, MFA, secure cookies, and anomaly detection. Even if one control fails, others still protect the system.
Strong web security is not a single feature but a layered system of controls. By combining safe coding practices, secure configurations, and continuous monitoring, you can significantly reduce the risk of common vulnerabilities.
Would you like this adapted into a checklist for developers or expanded with code examples in a specific framework like Node.js, Django, or Spring?


Rizwan Saleem — https://rizwansaleem.co

Sources

Top comments (0)