Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com Official Telegram Support (@PathubsSupport)
Pathubs

100% Free, Zero-Paywall Tech Career Roadmaps, In-Depth Practical Content, and Live Interactive Virtual Labs for Learners Worldwide.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
HomeResourcesFull Stack: Basic Web Security
OWASP Top 10 Fundamentals Zero Client Trust HTTPS & Transport Security AuthN vs AuthZ

Basic Web Security for Full Stack Developers

Master the foundational security principles every full-stack engineer needs in production. Understand why anything from the browser is inherently untrusted, eliminate injection attacks, defend against XSS and CSRF, and build applications with resilient defense-in-depth.

THE CARDINAL RULE: Never trust anything from the client. Query parameters, request bodies, HTTP headers, cookies, and hidden form fields can all be trivially manipulated. The server is your only security trust boundary.

Client BrowserUntrusted input source
➔
HTTPS / TLSEncrypted transit + HSTS
➔
ValidationServer rejects malformed
➔
AuthN & AuthZIdentity + Permission
➔
Safe LogicParameterized DB & CSP
OWASP Standards
Full Stack Architecture
Est. Time: ~35 Mins
Curriculum Outline (10 Core Sections)
1. Trust Nothing From the Client 2. HTTPS & Transport Security 3. Cross-Site Scripting (XSS) 4. SQL Injection (SQLi) 5. Cross-Site Request Forgery (CSRF) 6. Authentication vs Authorization 7. Essential HTTP Security Headers 8. 🔥 Live Security Checker 9. 🔥 Real-World Security Debugging 10. Final Full-Stack Security Challenge

1. Trust Nothing From the Client

Establishing the backend as the single trust boundary

Every piece of information that travels across the network originates from an environment controlled entirely by the user. Whether it is an HTML input, an HTTP request header, a query parameter, or a cookie, any client can forge any value.

Incoming Client HTTP PayloadHostile / Untrusted
// POST /api/profile/update
// Sent from browser form or curl command:
{
  "username": "alex",
  "bio": "Full Stack developer",
  "role": "admin",             // ❌ Forged client claim!
  "isSubscribed": true,        // ❌ Forged billing state!
  "discountPercent": 100       // ❌ Forged pricing!
}
Server-Side Independent VerificationSafe Trust Boundary
// In backend controller:
export async function updateProfile(req, res) {
  // 1. Identify verified caller via session token
  const userId = req.session.userId;

  // 2. Allow ONLY safe, editable fields
  const { bio } = req.body;

  // 3. Ignore client claims of 'role' or 'isSubscribed'!
  // The server looks up roles from verified database state:
  await db.query(
    'UPDATE users SET bio = $1 WHERE id = $2',
    [bio, userId]
  );
}
Why Client Trust Causes Catastrophic Breaches
If a backend does await User.update(req.body) (known as Mass Assignment), an attacker simply adds "role": "admin" or "isAdmin": true to their request body. The server must explicitly filter incoming fields and never allow client-controlled data to assign permissions or privileges.

2. HTTPS & Transport Security

Encrypting data in transit and protecting session tokens

Plain HTTP (Cleartext)

Data is sent in raw readable text across the internet. Anyone with access to the local Wi-Fi, ISP, or routers can inspect traffic.

GET /api/account HTTP/1.1
Host: mysite.com
Cookie: session_token=secret12345

// ⚠️ Eavesdroppers capture session_token in plain text!
HTTPS (HTTP over TLS)

End-to-end cryptographic encryption between browser and server. Shields passwords, tokens, and payloads from interception.

// Encrypted TLS Tunnel
[Ciphertext Payload: a9f83...d82]

// ✓ Only your server can decrypt the session token!
HSTS (Strict-Transport-Security)
An HTTP response header instructing the browser to never contact the site over insecure HTTP again.
Strict-Transport-Security: max-age=31536000; includeSubDomains
Secure Cookie Attributes
• Secure: Sent ONLY over HTTPS connections.
• HttpOnly: Inaccessible to JavaScript (blocks XSS theft).
• SameSite=Lax: Mitigates cross-origin CSRF leakage.

3. Cross-Site Scripting (XSS)

Preventing untrusted data from executing as code in user browsers

Cross-Site Scripting happens when user-controlled data is injected into web pages without proper encoding or sanitization, causing the victim browser to interpret and execute it as active JavaScript.

Vulnerable HTML RenderingUnsafe DOM Injection
// Unsafe rendering:
const userBio = req.body.bio;

// ❌ If bio contains: "<img src=x onerror=alert(1)>"
// innerHTML evaluates and executes the tag!
element.innerHTML = userBio;

// In React:
<div dangerouslySetInnerHTML={{ __html: userBio }} />
Safe Context-Aware EncodingStandard Framework Protection
// Safe rendering (React / Vue / Angular auto-escape):
const userBio = req.body.bio;

// ✅ Characters converted to harmless text entities:
// "<" becomes "&lt;", ">" becomes "&gt;"
return <div>{userBio}</div>;

// If rich HTML is intentionally allowed:
import DOMPurify from 'dompurify';
const cleanHtml = DOMPurify.sanitize(userBio);
Core OWASP Defense Principles for XSS
1. Output Encoding: Always encode untrusted data before rendering it in HTML body, attributes, or scripts.
2. Framework Auto-Escaping: Let React or modern template engines safely interpolate text via {value}.
3. Avoid Danger APIs: Eliminate dangerouslySetInnerHTML, innerHTML, and document.write.
4. Sanitize When Permitted: If you must render markdown or user HTML, sanitize strictly using battle-tested libraries like DOMPurify.

4. SQL Injection (SQLi)

Separating data from instructions with parameterized queries

SQL Injection happens when untrusted user input is directly concatenated into a database query string. The database engine cannot distinguish between developer instructions and user data, allowing input to alter query logic.

Unsafe Query ConcatenationFatal SQL Injection Risk
// ❌ VULNERABLE: Direct string interpolation
const email = req.body.email;
const query = "SELECT * FROM users WHERE email = '" + email + "'";

// The database parses the whole string at once.
// Input can inject quotes and SQL keywords to
// bypass authentication or dump tables!
Safe Parameterized QueryStandard Prepared Statement
// ✅ SECURE: Parameterized Query ($1, $2, or ?)
const email = req.body.email;
const query = "SELECT * FROM users WHERE email = $1";

// The database compiles the SQL syntax FIRST.
// Then the parameter is passed as literal DATA.
await db.query(query, [email]);
The Mental Model: Why Parameterized Queries Always Win
When you use parameterized queries (prepared statements), the database performs a two-step process:
1. Compilation: The database parses the SQL statement and builds the execution tree.
2. Binding: The parameter values are inserted into designated placeholder slots.
Even if a user input contains quotes, semicolons, or SQL clauses, the database treats it strictly as a string literal. It is physically impossible for user data to change the query structure.

5. Cross-Site Request Forgery (CSRF)

Preventing unauthorized actions executed via ambient credentials

In CSRF, an attacker's site tricks an authenticated user's browser into performing an unwanted state-changing action on your web application (such as transferring funds, changing an email, or deleting records).

Crucial Distinction: CSRF ≠ CORS
CORS (Cross-Origin Resource Sharing) relaxes the Same-Origin Policy so legitimate foreign origins can read responses.
CSRF occurs because browsers automatically include cookies with cross-site requests (e.g. from an HTML form on an attacker site). CORS does not stop form POST submissions from firing.
SameSite Cookies

Configure cookies with SameSite=Lax or SameSite=Strict. The browser will refuse to send the cookie on cross-site state-changing POST requests.

Anti-CSRF Tokens

The server generates a cryptographically random, unpredictable token per session. State-changing forms must include this token in headers or payloads.

Custom Request Headers

Requiring headers like Authorization: Bearer ... or X-Requested-With prevents simple form attacks, as browsers cannot add custom headers without CORS preflight.

6. Authentication vs Authorization

Separating identity verification from permission management

Authentication (AuthN)

Question: "Who are you?"

Verifies identity using credentials, passwords, biometrics, session cookies, or signed JWTs.

Example: User logs in with email + password (✓ Verified)
Authorization (AuthZ)

Question: "What are you allowed to do?"

Determines whether an already authenticated user has permission to view, edit, or delete a specific resource.

Example: User 12 attempts DELETE /api/users/42 (✗ Forbidden 403)
The Most Common Full-Stack Trap
Developers frequently write middleware that checks if a user is logged in (Authentication) and assume their API is secure.

Being logged in does NOT grant permission to do everything.If user Alice can request GET /api/invoices/999and inspect Bob's private invoice, you have anInsecure Direct Object Reference (IDOR). The endpoint must verify object ownership: WHERE invoice_id = $1 AND user_id = $2.

7. Essential HTTP Security Headers

Directing browser-level security policies

HTTP response headers declare security rules that modern browsers enforce directly on client devices. Here are the three most essential headers every full-stack developer should configure:

Content-Security-Policy (CSP)

Restricts where the browser can load scripts, styles, images, and frames from, effectively neutralizing unauthorized inline script execution (XSS mitigation).

Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; object-src 'none';
Strict-Transport-Security (HSTS)

Forces the browser to connect exclusively over HTTPS, even if the user manually types http:// or clicks an insecure link.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options

Prevents MIME-sniffing. Forces browsers to strictly honor the declared Content-Type, preventing text or image files from executing as scripts.

X-Content-Type-Options: nosniff

8. 🔥 Live Security Checker

Interactive full-stack application defense audit

Audit this fictional Full Stack web application. Toggle each architectural layer between RISKY and SECURE, then run the audit to observe how defense-in-depth eliminates vulnerabilities and protects users.

Current System Security Score
0%/ 100% Defense Level
🚨 Severely Vulnerable
Transport Layer & Protocol

How data travels between client browser and backend server.

Database Query Construction

How user input is incorporated into database queries.

User-Generated Content in UI

How user profile bios and forum comments are rendered.

Role & Privilege Assignment

How administrative privileges and user roles are verified.

Authentication Cookie Configuration

How authentication tokens and session cookies are stored in browser.

HTTP Security Headers

Browser defense policies declared via HTTP response headers.

9. 🔥 Real-World Security Debugging

Analyze critical production scenarios and architectural traps

Evaluate 4 real-world full-stack security scenarios. Select the correct architectural analysis for each incident to reveal the technical rationale.

Scenario #1

Scenario 1: Hiding the "Delete User" Button in Frontend

// React Client Component ('use client')
export function UserSettings({ user, currentUser }) {
  return (
    <div>
      <h3>User: {user.name}</h3>
      {currentUser.isAdmin && (
        <button onClick={() => fetch(`/api/users/${user.id}`, { method: 'DELETE' })}>
          Delete User
        </button>
      )}
    </div>
  );
}
A junior developer hides the "Delete User" button in the React UI if currentUser.isAdmin is false. Is this an effective authorization control?
Scenario #2

Scenario 2: Validating Input Only in Client JavaScript

// Frontend Form Submit Handler
function handleSubmit(event) {
  event.preventDefault();
  if (age < 18 || !email.includes('@')) {
    alert("Invalid input!");
    return;
  }
  // Sends POST /api/register
  fetch('/api/register', { method: 'POST', body: JSON.stringify({ email, age }) });
}
The developer validated that age >= 18 on the client. Can the backend registration route trust that the received age is valid without its own check?
Scenario #3

Scenario 3: Inserting User Bio with innerHTML

// UserProfile.js
async function renderProfile(userId) {
  const res = await fetch('/api/profile/' + userId);
  const data = await res.json();
  
  // Inserting user-controlled bio directly into DOM
  document.getElementById('bio-container').innerHTML = data.bio;
}
A developer uses innerHTML to render user profile bios so users can format text with basic tags. What critical security vulnerability should you immediately investigate?
Scenario #4

Scenario 4: Cross-Site Form Submitting to Authenticated Session

<!-- Attacker site (evil.com) -->
<form action="https://bank.com/api/transfer" method="POST">
  <input type="hidden" name="toAccount" value="attacker99" />
  <input type="hidden" name="amount" value="5000" />
</form>
<script>document.forms[0].submit();</script>
A victim visits evil.com while logged into bank.com. If bank.com uses cookies without SameSite or anti-CSRF tokens, what attack occurs?

10. Final Full-Stack Security Challenge

Harden a complete learning platform application

You are deploying a modern learning platform with login, profiles, course creation, comments, and an admin dashboard. Choose the secure implementation for each architectural decision.

1. User Authentication & Login

Threat: Credential interception & token exposure

2. Course Enrollment Query

Threat: Database manipulation via courseId parameter

3. Student Comment Section

Threat: Arbitrary script execution via comment bodies

4. Course Deletion Endpoint

Threat: Insecure Direct Object Reference / Missing Authorization

5. Password Reset Form

Threat: Unauthorized cross-site state changes

6. Application Response Headers

Threat: MIME confusion & unconstrained resource loading
The Complete Full-Stack Web Security Mental Model
CLIENT ➔ UNTRUSTED INPUT ➔ HTTPS ➔ SERVER VALIDATION ➔ AUTHENTICATION ➔ AUTHORIZATION ➔ SAFE DB / BUSINESS LOGIC ➔ SECURE RESPONSE
Authentication vs Authorization

Authentication proves who you are. Authorization determines what you can do. Always check permissions at the object level.

Parameterized Queries for SQL

Never concatenate user input into SQL queries. Prepared statements compile SQL before binding data, guaranteeing safety.

Context-Aware Output Encoding

Prevent XSS by letting frameworks escape text bindings automatically. Sanitize with DOMPurify only when intentional HTML is required.

Defense-in-Depth & Headers

Combine HTTPS, HSTS, Secure HttpOnly SameSite cookies, and Content-Security-Policy so that if one layer slips, others protect the user.