Web Security & Mobile App Development
OWASP Top 10 Web Vulnerabilities: Implementing Enterprise-Grade Security in Node.js & React
Concrete Node.js and React controls for each OWASP Top 10 category: authorization models, CSP, dependency integrity, secrets and logging.
The OWASP Top 10 is often treated as a checklist for a penetration test. In a Node.js and React stack it is more useful as an architecture review: most categories map to a specific design decision rather than a missing library. Broken access control, for instance, is a data-layer authorisation problem — no framework middleware fixes it.
The objective for lead engineers is enforceable controls: authorisation adjacent to data, output encoding by default, a strict Content Security Policy, dependency integrity in CI, and logging that supports incident response.
Access Control and Authorisation
- Authorise per resource in the data layer. A gateway that verifies a token proves identity, not entitlement to a specific row.
- Never trust client-supplied identifiers for ownership. Derive scope from the session subject, then filter queries by it.
- Deny by default: every new endpoint requires an explicit policy, enforced by a shared guard rather than per-route ad hoc checks.
- Store roles in a dedicated table with server-side evaluation. Roles in JWT claims or client storage are privilege-escalation vectors when not re-verified.
Injection and Output Handling
- Parameterised queries only; never interpolate input into SQL, and never pass user input to shell commands.
- Validate all input at the boundary with a schema validator, rejecting unknown fields rather than silently accepting them.
- In React, treat
dangerouslySetInnerHTMLas a security review trigger; sanitise server-side with an allowlist if rich content is unavoidable. - Block SSRF by allowlisting outbound hosts, resolving DNS and rejecting private ranges, and disabling redirects on server-side fetches of user-supplied URLs.
- Prevent prototype pollution and unsafe deserialisation by validating shapes and avoiding recursive merge of untrusted objects.
Transport, Headers and Sessions
Set security headers centrally: a nonce-based Content-Security-Policy without unsafe-inline, Strict-Transport-Security with a long max-age, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and a restrictive Permissions-Policy. Sessions use HttpOnly, Secure, SameSite cookies with short-lived access tokens, rotating refresh tokens, server-side revocation and re-authentication for sensitive actions.
Control Mapping
| OWASP category | Node.js / React control | Verification |
|---|---|---|
| Broken access control | Row-level authorisation in data layer | Negative tests per role |
| Cryptographic failures | TLS everywhere, Argon2id hashing, KMS-held keys | Config audit |
| Injection | Parameterised queries, schema validation | SAST plus fuzzing |
| Insecure design | Threat model per feature | Design review gate |
| Security misconfiguration | Central headers, no debug in prod | Automated header scan |
| Vulnerable components | Lockfile audit, pinned versions, SBOM | CI dependency gate |
| Auth failures | Short-lived tokens, MFA, rate-limited login | Auth test suite |
| Integrity failures | Signed artifacts, verified webhooks | Pipeline attestation |
| Logging failures | Structured audit log, alerting | Incident drill |
| SSRF | Outbound allowlist, private-range rejection | Targeted test cases |
Blueprint: Nonce CSP and Safe Outbound Fetch
import { randomBytes } from "crypto";
import { lookup } from "dns/promises";
export function securityHeaders(nonce: string) {
return {
"Content-Security-Policy": [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}'`,
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'none'",
"require-trusted-types-for 'script'",
].join("; "),
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
};
}
export const newNonce = () => randomBytes(16).toString("base64");
const ALLOWED_HOSTS = new Set(["api.partner.com", "cms.internal"]);
export async function safeFetch(rawUrl: string) {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !ALLOWED_HOSTS.has(url.hostname)) {
throw new Error("blocked_host");
}
const { address } = await lookup(url.hostname);
if (/^(10\.|127\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(address)) {
throw new Error("blocked_private_range");
}
return fetch(url, { redirect: "error" });
}Strategic Action Plan: 90 Days
- Days 1–12 — Threat model and inventory. Map data classes, trust boundaries, external integrations and every endpoint's current authorisation check.
- Days 13–30 — Fix authorisation. Introduce a deny-by-default guard, move entitlement checks into the data layer, and add negative tests per role.
- Days 31–50 — Harden the perimeter. Ship nonce-based CSP and full header set, rotate secrets into a managed store, and enforce rate limits on authentication paths.
- Days 51–70 — Secure the supply chain. Pin dependencies, fail CI on high-severity advisories, generate an SBOM, and verify webhook and artifact signatures.
- Days 71–90 — Prove detection. Add structured audit logging for authentication and authorisation events, alert on anomalies, then run a tabletop incident exercise and a third-party penetration test.
Frequently Asked Questions
Why is broken access control still the most common vulnerability?
Because it is a per-resource logic problem, not a configuration one. Authentication middleware proves who the caller is, then individual handlers decide what they may touch — and one handler that trusts a client-supplied ID exposes everything. Centralising entitlement checks in the data layer and writing negative tests per role is the only durable fix.
Where should roles and permissions be stored?
In a dedicated server-side table, evaluated by the backend on every privileged operation. Storing roles on a user profile row that clients can update, or reading them from client storage or unverified token claims, allows privilege escalation. Use a security-definer function or equivalent server check, and never let the browser assert its own authority.
Is a Content Security Policy worth the implementation effort?
Yes. A nonce-based policy without unsafe-inline blocks the majority of stored and reflected XSS payload delivery even when an injection defect exists, and it constrains compromised third-party scripts. Roll it out in report-only mode first, fix violations, then enforce — and keep script sources explicitly allowlisted rather than using wildcards.
How do we manage dependency risk in a large Node.js project?
Pin exact versions with a committed lockfile, fail the build on high-severity advisories, generate and store an SBOM per release, and review new transitive dependencies during code review. Reduce surface area by removing packages that wrap a few lines of standard library code, and verify build artifacts are produced by your pipeline rather than fetched at runtime.