Tutorials Logic, IN info@tutorialslogic.com
OWASP

Top 50 Cybersecurity & OWASP Interview Questions

Cybersecurity and OWASP interview questions covering web security, authentication, authorization, injection, XSS, CSRF, logging, and secure design.

01

What is OWASP, and why is it important in application security interviews?

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. A strong answer should connect OWASP to real engineering work: threat modeling, secure code review, dependency scanning, authentication design, logging, and release checks.

02

What is the OWASP Top 10?

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. Interviewers expect you to explain risk, impact, prevention, and testing for each category.

03

What is broken access control?

Broken access control happens when users can perform actions or access data they should not be allowed to access. Examples include viewing another user's order by changing an ID, calling admin APIs without an admin role, or bypassing server-side checks through a hidden UI field. The fix is server-side authorization on every sensitive action, object-level checks, deny-by-default behavior, and automated tests for horizontal and vertical privilege boundaries.

04

What is IDOR, and how do you prevent it?

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. Obscure IDs help reduce guessing, but they do not replace authorization.

Example
// Safer: query is scoped to the current user.
$invoice = Invoice::where('id', $invoiceId)
    ->where('user_id', $currentUser->id)
    ->firstOrFail();
05

How do authentication and authorization differ?

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. Checking whether that user can delete a project, approve a refund, or read a private record is authorization. A common interview mistake is assuming authentication is enough. Every sensitive resource and operation still needs authorization checks.

06

What is SQL injection?

SQL injection occurs when untrusted input is mixed into a SQL query as executable syntax. An attacker can change the meaning of the query, bypass login, read unauthorized data, modify records, or damage the database. Prevent it with parameterized queries, safe ORM APIs, allowlisted dynamic fields, least-privilege database accounts, and careful error handling. Escaping alone is easy to get wrong and should not be the primary defense.

Example
// Vulnerable
$sql = "SELECT * FROM users WHERE email = '$email'";

// Safer
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
07

Can prepared statements fully prevent SQL injection?

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. For those dynamic parts, use allowlists. For example, allow only known sort fields such as created_at or name, and map user choices to safe SQL identifiers.

08

What is NoSQL injection?

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.

Example
// 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 });
09

What is command injection?

Command injection occurs when user input reaches an operating system command and changes what the shell executes. For example, passing a filename into a shell command can become dangerous if attackers add separators or flags. Avoid shell execution when possible. Use language APIs, pass arguments as arrays, validate inputs against strict allowlists, and never concatenate raw user input into shell strings.

Example
// Risky
exec("convert " + req.body.file + " output.png");

// Safer: avoid shell parsing and pass arguments separately
spawn("convert", [safeInputPath, "output.png"], { shell: false });
10

What is cross-site scripting?

Cross-site scripting, or XSS, happens when attacker-controlled content is executed as JavaScript in another user's browser. It can steal session data, perform actions as the victim, modify page content, or capture sensitive input. The main defense is context-aware output encoding, safe templating, sanitization for allowed HTML, Content Security Policy, and avoiding dangerous APIs such as innerHTML for untrusted data.

11

What is the difference between reflected, stored, and DOM-based XSS?

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. DOM-based XSS happens when client-side JavaScript reads untrusted data and writes it into a dangerous sink. Stored XSS is often highest impact because one malicious payload can affect many users.

12

How do you prevent XSS in frontend code?

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. The safest pattern is to render user input as text, not markup.

Example
// Risky
profileBox.innerHTML = user.bio;

// Safer for plain text
profileBox.textContent = user.bio;
13

What is Content Security Policy?

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. Start with report-only mode, inspect violations, remove unsafe-inline where possible, use nonces or hashes for approved scripts, and avoid overly broad sources such as *.

Example
Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-randomValue';
  object-src 'none';
  base-uri 'self';
  frame-ancestors 'none';
14

What is CSRF?

Cross-site request forgery, or CSRF, tricks a logged-in user's browser into sending an unwanted state-changing request to a trusted site. The attacker relies on cookies being sent automatically. Defenses include SameSite cookies, CSRF tokens for state-changing requests, checking origin or referer where appropriate, and avoiding GET requests for actions that change state. APIs using bearer tokens in headers are less exposed to classic CSRF than cookie-only sessions.

15

How do CSRF tokens work?

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. An attacker on another site cannot read the token due to browser same-origin rules, so their forged request should fail. Tokens must be unique enough, validated server-side, and not leaked in URLs.

16

What cookie flags improve session security?

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.

Example
Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax
17

What is session fixation?

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. Also expire old sessions, set secure cookie flags, and reject session IDs supplied through URLs. In interviews, mention that authentication changes should create a new trusted session context.

18

How should passwords be stored securely?

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. Each password needs its own salt. Add rate limiting, breached-password checks, MFA, and secure reset flows. If a database leaks, strong password hashing slows offline cracking.

Example
$hash = password_hash($password, PASSWORD_ARGON2ID);

if (! password_verify($passwordAttempt, $hash)) {
    throw new RuntimeException('Invalid credentials');
}
19

What makes a password reset flow secure?

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. Log reset attempts and alert on unusual volume or suspicious behavior.

20

What is MFA, and what are common implementation concerns?

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.

21

What JWT mistakes are common in interviews?

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. Treat claims as authorization inputs, not automatic permission grants. For browser apps, think carefully about XSS and token storage.

Example
const payload = jwt.verify(token, publicKey, {
  algorithms: ["RS256"],
  issuer: "https://auth.example.com",
  audience: "orders-api"
});
22

What is cryptographic failure?

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. The fix includes TLS, strong password hashing, managed key storage, modern algorithms, rotation plans, and minimizing sensitive data collection.

23

How should API authorization be designed?

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. Do not trust client-side hidden fields, menu visibility, or route guards as security controls. For multi-tenant systems, every query should be scoped to the tenant and the authenticated principal. Add negative tests for forbidden access.

24

What is least privilege?

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. Least privilege is not a one-time setting; it needs maintenance as systems and teams change.

25

What is security misconfiguration?

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. Prevent it with hardened baselines, infrastructure as code, automated checks, environment-specific configs, and regular review of production settings.

26

How can CORS become a security problem?

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. CORS is not authentication. The server must still authorize each request. Configure exact trusted origins, avoid wildcard origins with credentials, and test browser behavior for cookies, tokens, preflight requests, and sensitive endpoints.

Example
Risky:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Safer:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
27

What security headers should a web application use?

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. A good interview answer explains the purpose of each header and warns against copy-pasting strict policies without testing, because CSP and framing rules can break legitimate functionality.

28

What is SSRF?

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.

Example
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
29

What is secure file upload?

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. Never trust the original filename or MIME type alone.

30

What is path traversal?

Path traversal occurs when attackers use input such as ../ to access files outside the intended directory. It can expose source code, credentials, logs, or system files. Prevent it by avoiding direct filesystem paths from user input, mapping IDs to known files, normalizing and validating paths, enforcing an allowlisted base directory, and using safe file APIs. Do not rely only on string replacement.

Example
$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');
}
31

What is insecure deserialization?

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. Prefer simple formats such as JSON with schema validation, sign or encrypt trusted tokens, and never deserialize data unless the source and type are tightly controlled. Review framework-specific risks such as PHP object injection or Java gadget chains.

32

What are software and data integrity failures?

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. Interviewers often connect this category to supply chain security.

33

How do vulnerable components create security risk?

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. Manage this risk with dependency inventories, lockfiles, software composition analysis, patch SLAs, container scanning, minimal images, and removing unused packages. The answer should mention prioritizing based on exploitability, exposure, and business impact.

34

What is dependency scanning?

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. Good teams track severity, exploitability, reachable code, fixed versions, and ownership. Do not blindly upgrade everything without testing, but do not ignore critical internet-exposed vulnerabilities either.

35

What is secret management?

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. Use a secret manager, environment-specific access controls, short-lived credentials where possible, and automated detection for accidental leaks. Rotation should be practiced before an incident.

36

What should be logged for security monitoring?

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. Logs are only useful if someone alerts on and reviews them.

37

What are security logging and monitoring failures?

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. Fix it with structured logs, centralized collection, alert rules, dashboards, retention, incident playbooks, and regular testing. A strong answer should mention both too little logging and noisy alerts that teams learn to ignore.

38

How do you design rate limiting?

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. Choose limits based on endpoint risk, user experience, and attack patterns. Add clear error responses, backoff, monitoring, and bypass rules for trusted internal traffic only when justified. Rate limits should complement authentication and bot defenses.

Example
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
39

What is threat modeling?

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. Then rank threats and define mitigations. A practical model for a payment flow might examine account takeover, tampered amounts, replayed webhooks, unauthorized refunds, leaked keys, and missing audit logs. The best output is actionable engineering work, not a decorative diagram.

40

How would you review a pull request for security issues?

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. A good review is specific: identify the risky path, the possible impact, and the smallest safe fix.

41

What is secure API input validation?

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. Use schema validators where possible and reject unknown fields for sensitive APIs. Validation reduces accidental bugs and malicious payloads, but it does not replace output encoding, authorization, or parameterized queries.

Example
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);
42

What is output encoding?

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. For example, encoding < as < helps in HTML text but is not enough inside a JavaScript string. Modern templating frameworks usually encode by default, but raw HTML escape hatches require careful review.

43

How do redirects become vulnerable?

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. Prevent this with allowlisted relative paths or known domains. Do not redirect directly to arbitrary returnUrl values. Also validate URL parsing carefully because encoded values, protocol-relative URLs, and mixed-case schemes can bypass weak checks.

Example
$allowed = ['/dashboard', '/settings', '/billing'];
$next = $_GET['next'] ?? '/dashboard';

if (! in_array($next, $allowed, true)) {
    $next = '/dashboard';
}

header('Location: ' . $next);
44

What is clickjacking?

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. Clickjacking matters for admin panels, payment pages, account settings, and any UI where a click can trigger a meaningful action.

45

How should incident response work for a web application?

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. A mature answer mentions runbooks, severity levels, roles, timelines, post-incident review, and practiced drills.

46

How do you explain secure design in an interview?

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. It is different from patching a bug after release. For example, designing multi-tenant queries to always require tenant scope is safer than relying on developers to remember the check in every controller.

47

What is defense in depth?

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. The goal is not to add random tools; each layer should address a specific failure mode and be testable.

48

How would you secure a login endpoint?

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. Also test lockout behavior so attackers cannot easily cause denial of service.

49

How would you secure an admin dashboard?

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.

50

How would you answer a scenario question about a public bucket or exposed files?

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. Rotate any exposed secrets, notify the right stakeholders, preserve evidence, and fix the root cause with policy, tests, and monitoring. A strong answer avoids panic and shows an incident-response sequence: contain, investigate, recover, communicate, and prevent recurrence.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.