Cybersecurity and OWASP interview questions covering web security, authentication, authorization, injection, XSS, CSRF, logging, and secure design.
OWASP is the Open Worldwide Application Security Project, a community that publishes practical security guidance such as the OWASP Top 10, API Security Top 10, ASVS, Cheat Sheets, and testing guides. In interviews, OWASP matters because it gives a shared vocabulary for common application risks.
The OWASP Top 10 is a list of major web application security risk categories, such as broken access control, cryptographic failures, injection, insecure design, security misconfiguration, vulnerable components, authentication failures, integrity failures, logging failures, and SSRF. It is not a complete checklist, but it is a useful baseline for developers and security teams.
Broken access control lets users reach data or actions outside their permissions. Enforce authorization on the server for every sensitive resource and operation.
Insecure Direct Object Reference, or IDOR, is a broken access control issue where an attacker changes an object identifier to access another user's resource. For example, changing /invoices/1001 to /invoices/1002 should not expose someone else's invoice. Prevent IDOR by checking ownership or permissions on the server for each object, using scoped database queries, and writing negative authorization tests.
// Safer: query is scoped to the current user.
$invoice = Invoice::where('id', $invoiceId)
->where('user_id', $currentUser->id)
->firstOrFail();
Authentication verifies who the user is, while authorization decides what the authenticated user is allowed to do. Logging in with a password or passkey is authentication.
SQL injection occurs when untrusted input changes executable SQL. Use parameterized queries for values and allowlists for dynamic identifiers such as sort columns.
// Vulnerable
$sql = "SELECT * FROM users WHERE email = '$email'";
// Safer
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
Prepared statements prevent injection for values when used correctly, but they do not automatically make every SQL pattern safe. Table names, column names, sort directions, and raw SQL fragments cannot usually be bound as normal parameters.
NoSQL injection happens when untrusted input changes a NoSQL query structure. For example, if a login API accepts JSON and passes it directly into a MongoDB query, an attacker may submit operators such as $ne or $gt instead of a plain string. Prevent it by validating types, rejecting unexpected object structures, using schema validation, avoiding direct query object construction from request bodies, and using safe framework APIs.
// Risky if req.body.email can be an object like {"$ne": null}
const user = await users.findOne({ email: req.body.email });
// Safer type check
if (typeof req.body.email !== "string") throw new Error("Invalid email");
const user = await users.findOne({ email: req.body.email });
Command injection occurs when user input changes what a shell executes. Avoid the shell where possible, or pass validated arguments separately instead of building a command string.
// Risky
exec("convert " + req.body.file + " output.png");
// Safer: avoid shell parsing and pass arguments separately
spawn("convert", [safeInputPath, "output.png"], { shell: false });
Cross-site scripting executes attacker-controlled content in another user's browser. The primary defense is context-aware output encoding, with sanitization only when HTML input is intentionally allowed.
Reflected XSS appears when input from the current request is immediately returned in the response. Stored XSS is saved in the application, such as a comment or profile field, and later shown to other users.
Use framework escaping, avoid writing untrusted data into HTML sinks, sanitize only when users are allowed to submit HTML, and encode output for the right context. Text content, HTML attributes, JavaScript strings, CSS, and URLs have different escaping needs. Content Security Policy can reduce impact, but it should be treated as defense in depth.
// Risky
profileBox.innerHTML = user.bio;
// Safer for plain text
profileBox.textContent = user.bio;
Content Security Policy, or CSP, is a browser security control that restricts where scripts, styles, images, frames, and other resources can load from. It helps reduce the impact of XSS by blocking inline scripts and untrusted script sources when configured well.
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-randomValue';
object-src 'none';
base-uri 'self';
frame-ancestors 'none';
CSRF tricks a logged-in browser into sending an unwanted state-changing request. SameSite cookies and verified CSRF tokens are the usual defenses for cookie-based sessions.
A CSRF token is an unpredictable value generated by the server and tied to the user session or request context. The application includes it in forms or headers, and the server verifies it before accepting state-changing actions.
HttpOnly prevents JavaScript from reading the cookie, Secure sends it only over HTTPS, SameSite limits cross-site sending, and an appropriate Path or Domain narrows where the cookie applies. For session cookies, use Secure, HttpOnly, and SameSite=Lax or Strict depending on the login flow. SameSite=None requires Secure and is usually needed only for legitimate cross-site use cases.
Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax
Session fixation occurs when an attacker causes a victim to use a known session ID, then uses that ID after the victim authenticates. Prevent it by regenerating the session identifier after login, privilege elevation, and sensitive account changes.
Passwords should be stored using a slow, salted, adaptive password hashing algorithm such as Argon2id, bcrypt, or PBKDF2 with strong parameters. Never store plaintext passwords or fast hashes such as raw MD5 or SHA-256.
$hash = password_hash($password, PASSWORD_ARGON2ID);
if (! password_verify($passwordAttempt, $hash)) {
throw new RuntimeException('Invalid credentials');
}
A secure reset flow uses single-use, high-entropy tokens with short expiration, sends tokens through a trusted channel, avoids revealing whether an email exists, invalidates tokens after use, and may invalidate existing sessions after password change. The reset page should require the token and new password only, not security questions.
Multi-factor authentication requires more than one type of proof, such as password plus authenticator app, passkey, hardware key, or push approval. It reduces account takeover risk, but implementation must handle recovery codes, enrollment security, phishing-resistant methods, step-up authentication for sensitive actions, and support workflows. SMS is better than no MFA but weaker than authenticator apps, WebAuthn, or hardware-backed passkeys.
Common JWT mistakes include accepting alg=none, failing to verify the signature, trusting claims without validation, using weak secrets, storing tokens insecurely, issuing very long-lived access tokens, and not checking issuer, audience, expiration, and key rotation. A JWT is only trustworthy after verification.
const payload = jwt.verify(token, publicKey, {
algorithms: ["RS256"],
issuer: "https://auth.example.com",
audience: "orders-api"
});
Cryptographic failure means sensitive data is exposed because encryption, hashing, key management, or transport protection is missing or misused. Examples include sending credentials over HTTP, storing passwords with fast hashes, using hardcoded encryption keys, disabling certificate validation, or exposing sensitive data in logs.
API authorization should be checked on the server for each sensitive action and resource. Use scopes, roles, ownership checks, tenant boundaries, and policy functions that are easy to test.
Least privilege means users, services, tokens, database accounts, and jobs receive only the permissions needed to perform their duties. It limits blast radius when a credential is stolen or a component is compromised. In practice, use narrow roles, short-lived credentials, separate admin accounts, environment isolation, and regular access reviews.
Security misconfiguration occurs when defaults, permissions, headers, cloud settings, debug modes, or network rules leave a system exposed. Examples include public storage buckets, verbose error pages, default admin credentials, directory listing, open database ports, missing security headers, or overly permissive CORS.
CORS controls which browser origins can read responses from an API. It becomes risky when an API allows every origin while also allowing credentials, or when it reflects arbitrary Origin headers.
Risky:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Safer:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Important headers include Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options, frame-ancestors or X-Frame-Options, Referrer-Policy, and secure cookie attributes. Headers reduce attack surface, but they do not replace secure code.
Server-side request forgery happens when an attacker controls a server-side URL request and makes the server call internal systems, cloud metadata endpoints, or restricted services. It is common in URL previewers, file importers, webhook testers, and image fetchers. Prevent SSRF with strict allowlists, URL parsing, DNS and IP validation, blocking private network ranges, disabling redirects where risky, timeouts, and network egress controls.
Block requests to internal ranges such as:
127.0.0.0/8
10.0.0.0/8
172.16.0.0/12
192.168.0.0/16
169.254.0.0/16
Secure file upload means accepting files without allowing malware, script execution, path traversal, storage abuse, or sensitive data exposure. Validate file size, extension, content type, and magic bytes; store uploads outside the web root or in object storage; generate server-side filenames; scan risky files; and serve downloads with safe headers.
Path traversal uses input such as ../ to escape an intended directory. Resolve against a fixed base path and reject any result outside it.
$base = realpath(__DIR__ . '/uploads');
$target = realpath($base . DIRECTORY_SEPARATOR . $requestedName);
if ($target === false || ! str_starts_with($target, $base . DIRECTORY_SEPARATOR)) {
throw new RuntimeException('Invalid file path');
}
Insecure deserialization happens when an application rebuilds objects from untrusted serialized data and triggers unexpected behavior, data tampering, or remote code execution. Avoid accepting serialized objects from users.
Integrity failures happen when code, updates, plugins, CI/CD steps, or data can be modified without proper verification. Examples include unsigned updates, compromised build pipelines, untrusted dependencies, and unsafe deserialization. Defenses include signed artifacts, dependency lockfiles, protected branches, CI permissions, artifact provenance, checksum validation, code review, and environment separation.
Vulnerable components are outdated libraries, frameworks, containers, plugins, or transitive dependencies with known flaws. Attackers often scan for publicly known vulnerabilities because exploit details may already exist.
Dependency scanning checks direct and transitive packages for known vulnerabilities and license or policy issues. It should run in CI, on pull requests, and regularly for deployed applications because new CVEs can appear after release.
Secret management is the controlled storage, access, rotation, and auditing of values such as API keys, database passwords, signing keys, and tokens. Secrets should not be committed to source control, embedded in Docker images, or printed in logs.
Log authentication events, failed logins, privilege changes, password resets, MFA changes, access-denied events, admin actions, suspicious input, rate-limit triggers, webhook failures, and high-risk data access. Logs should include timestamps, request IDs, user or service identity, source IP where appropriate, and outcome. Avoid logging passwords, tokens, card data, or sensitive personal data.
This OWASP category covers missing, weak, or unactionable detection. A system can be compromised for weeks if failed logins, privilege abuse, suspicious exports, and admin changes are not logged or alerted.
Rate limiting restricts how often a user, IP, token, tenant, or client can call an endpoint. It protects login forms, password reset flows, APIs, expensive searches, and public endpoints from abuse.
Example policy:
Login attempts: 5 per account per 10 minutes
Password reset: 3 per email per hour
Public search API: 60 per IP per minute
Admin export: 10 per admin per day
Threat modeling is a structured way to identify what can go wrong before building or releasing a system. Start with assets, actors, trust boundaries, data flows, and abuse cases.
Look for new inputs, authorization changes, SQL or shell calls, file handling, redirects, secrets, dependency changes, logging of sensitive data, CORS or header changes, and admin functionality. Ask what happens if the user is unauthenticated, authenticated as another tenant, or malicious. Check tests for negative cases.
Secure input validation checks that incoming data has the expected type, length, format, range, and allowed values before business logic uses it. Validation should happen server-side even if the frontend also validates.
const schema = z.object({
email: z.string().email(),
quantity: z.number().int().min(1).max(100),
plan: z.enum(["basic", "pro", "team"])
}).strict();
const input = schema.parse(req.body);
Output encoding converts special characters so the browser treats user-controlled data as text instead of executable code. Encoding must match the context: HTML body, HTML attribute, JavaScript string, CSS, or URL.
Open redirects occur when an application redirects users to attacker-controlled URLs. Attackers use them for phishing because the link starts on a trusted domain.
$allowed = ['/dashboard', '/settings', '/billing'];
$next = $_GET['next'] ?? '/dashboard';
if (! in_array($next, $allowed, true)) {
$next = '/dashboard';
}
header('Location: ' . $next);
Clickjacking tricks users into clicking a hidden or framed page, causing actions they did not intend. Defend with frame-ancestors in Content Security Policy or X-Frame-Options for older support. Sensitive actions should also require server-side authorization and sometimes re-authentication.
Incident response should define how the team detects, triages, contains, investigates, communicates, recovers, and learns from security events. For a suspected credential leak, steps may include revoking keys, rotating secrets, checking logs, blocking abusive traffic, preserving evidence, notifying stakeholders, and patching the root cause.
Secure design means building systems so risky behavior is difficult by default. It includes threat modeling, least privilege, safe defaults, clear trust boundaries, abuse-case thinking, defense in depth, and fail-safe behavior.
Defense in depth uses multiple layers of controls so one failure does not become a complete compromise. For example, a secure API may use authentication, authorization, input validation, parameterized queries, output encoding, rate limiting, logging, WAF rules, and least-privilege database access.
A secure login endpoint uses TLS, strong password hashing, account enumeration protection, rate limiting, MFA support, secure session cookies, session ID regeneration after login, logging, and alerting for suspicious attempts. It should not reveal whether the email or password was wrong. Add breached-password checks and step-up authentication for risky contexts.
Secure an admin dashboard with strong authentication, MFA, role-based or policy-based authorization, least-privilege roles, IAP or VPN if appropriate, audit logs, CSRF protection, secure cookies, short session lifetimes, approval workflows for sensitive actions, and clear separation from normal user features. Admin actions should be logged with actor, target, before-and-after values where safe, and request context.
First contain the exposure by removing public access or disabling the affected route. Then identify what data was exposed, for how long, and who accessed it from logs.
Use curated frontend, Java, Python, or cloud and DevOps packs with 200 questions, model answers, code examples, and a seven-day plan.
Combine four related topic areas into one focused role-preparation path.
Practise explaining code, design decisions, limitations, and failure modes.
Move from baseline review to a timed mock interview and final checklist.
Explore 500+ free tutorials across 20+ languages and frameworks.