DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Web Security Basics: CORS, CSP, XSS, CSRF — What Every Developer Must Know

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Web Security Basics: CORS, CSP, XSS, CSRF — What Every Developer Must Know

Security isn't optional — it's part of your job as a developer. Most breaches exploit well-known vulnerabilities that have been understood for years. Here are the five web security threats every developer must understand, with prevention strategies and code examples.

The Threat Landscape

Attack Severity OWASP Rank What It Does
XSS (Cross-Site Scripting) Critical #2 Injects malicious scripts into your pages
SQL Injection Critical #3 Executes arbitrary SQL on your database
CSRF (Cross-Site Request Forgery) High Dropped Tricks users into performing unwanted actions
CORS Misconfiguration High #5 Allows unauthorized cross-origin access
Insecure Authentication Critical #1 Weak auth allows account takeover

1. Cross-Site Scripting (XSS)

XSS happens when user input is rendered as HTML without sanitization. An attacker who can inject tags can steal cookies, session tokens, and sensitive data.</p> <div class="highlight"><pre class="highlight plaintext"><code>// ❌ Vulnerable: div.innerHTML = userComment; // Attacker: &lt;img src=x onerror="stealCookies()"&gt; // ✅ Safe: div.textContent = userComment; // Escapes HTML automatically // Or sanitize: import DOMPurify from 'dompurify'; div.innerHTML = DOMPurify.sanitize(userComment); </code></pre></div> <p><strong>React note:</strong> JSX auto-escapes by default — you&#39;re safe from XSS in standard rendering. The danger is dangerouslySetInnerHTML and direct DOM manipulation.</p> <h2> <a name="2-sql-injection" href="#2-sql-injection" class="anchor"> </a> 2. SQL Injection </h2> <p>Concatenating user input into SQL queries gives attackers full database access. Parameterized queries are the fix — use them 100% of the time.</p> <div class="highlight"><pre class="highlight plaintext"><code>// ❌ Vulnerable — attacker input: "1; DROP TABLE users;" const query = `SELECT * FROM users WHERE id = ${userId}`; // ✅ Safe — parameterized query const query = "SELECT * FROM users WHERE id = $1"; const result = await db.query(query, [userId]); // ORM users: Prisma/Drizzle parameterize automatically </code></pre></div><h2> <a name="3-crosssite-request-forgery-csrf" href="#3-crosssite-request-forgery-csrf" class="anchor"> </a> 3. Cross-Site Request Forgery (CSRF) </h2> <p>An attacker&#39;s site makes a request to your API using the victim&#39;s cookies. CSRF tokens ensure the request originated from your own frontend.</p> <div class="highlight"><pre class="highlight plaintext"><code>// Mitigation strategies: // 1. SameSite cookies (simplest, best): Set-Cookie: session=abc123; SameSite=Strict; HttpOnly; Secure // 2. CSRF token (additional layer): // Server sends a unique token; client includes it in requests // Modern frameworks (Next.js, Remix) handle this automatically // 3. Custom header requirement: // Browsers don't allow custom headers cross-origin // Require X-Requested-With or similar </code></pre></div><h2> <a name="4-cors-misconfiguration" href="#4-cors-misconfiguration" class="anchor"> </a> 4. CORS Misconfiguration </h2> <p>CORS (Cross-Origin Resource Sharing) controls which origins can access your API. The most common mistake: using a wildcard or reflecting the Origin header blindly.</p> <div class="highlight"><pre class="highlight plaintext"><code>// ❌ Vulnerable — allows any origin: Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true // Can't use with * // ❌ Vulnerable — reflects origin blindly: // If your server echoes back the request's Origin header, any domain can access // ✅ Safe — explicit allowlist: const allowedOrigins = ["https://myapp.com", "https://admin.myapp.com"]; const origin = req.headers.origin; if (allowedOrigins.includes(origin)) { res.setHeader("Access-Control-Allow-Origin", origin); } </code></pre></div><h2> <a name="5-content-security-policy-csp" href="#5-content-security-policy-csp" class="anchor"> </a> 5. Content Security Policy (CSP) </h2> <p>CSP is your last line of defense. It tells the browser what sources of scripts, styles, and other resources are allowed. A well-configured CSP makes XSS exploitation nearly impossible.</p> <div class="highlight"><pre class="highlight plaintext"><code>// Recommended CSP header: Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://js.stripe.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' https://api.myapp.com; frame-src https://js.stripe.com; // NO 'unsafe-inline' for scripts in production (use nonce/hash) </code></pre></div><h2> <a name="security-checklist" href="#security-checklist" class="anchor"> </a> Security Checklist </h2> <ul> <li><strong>Authentication:</strong> Use OAuth 2.0 / OIDC. Never roll your own crypto.</li> <li><strong>Passwords:</strong> bcrypt with cost factor 12+. Never store plaintext.</li> <li><strong>HTTPS:</strong> Everywhere. Redirect HTTP. HSTS header.</li> <li><strong>Dependencies:</strong> npm audit / snyk weekly. Auto-update minor patches.</li> <li><strong>Environment variables:</strong> Never commit .env files. Inject at runtime.</li> <li><strong>Rate limiting:</strong> Protect login and API endpoints from brute force.</li> <li><strong>Logging:</strong> Log auth events. Never log passwords or tokens.</li> </ul> <p><strong>Bottom line:</strong> Use parameterized queries, auto-escaping frameworks, SameSite cookies, CSP headers, and explicit CORS allowlists. Security is layers — implement them all, and a single failure won&#39;t compromise you. See also: <a href="///en/tech/rest-api-best-practices.html">REST API Best Practices</a> and <a href="///en/tech/api-design-patterns.html">API Design Patterns</a>.</p> <hr> <p><strong>Read the full article on <a href="https://dingjiu1989-hue.github.io/en/tech/web-security-basics.html">AI Study Room</a></strong> for complete code examples, comparison tables, and related resources.</p> <p><em>Found this useful? Check out more <a href="https://dingjiu1989-hue.github.io/en/">developer guides and tool comparisons</a> on AI Study Room.</em></p>

Top comments (0)