Web Security and OWASP Interview Questions and Answers
Last updated 2026-11-19
Security questions in developer interviews are not about exploiting systems. They check that you recognise common vulnerability classes in ordinary code and know the standard fix for each: parameterised queries for injection, output encoding and CSP for cross-site scripting, ownership checks for access control, and safe handling of passwords, sessions and tokens.
The questions follow the OWASP Top 10 categories, the most widely used list of web application risks. The 2021 edition is the one most interview material cites, and OWASP has published an update since, so check owasp.org for the current ordering and names. The same underlying issues recur across editions. Related topics appear in the backend developer and frontend developer question banks.
| Framework | OWASP Top 10 and OWASP cheat sheets |
|---|---|
| Core topics | Injection, XSS, CSRF, access control, authentication, SSRF, misconfiguration |
| Questions here | 18 |
The Top 10 categories in plain words (2021 edition)
- Broken access control: users act outside their permissions, for example by changing an ID in a URL.
- Cryptographic failures: sensitive data exposed through weak or missing encryption and hashing.
- Injection: untrusted input interpreted as code, including SQL and cross-site scripting.
- Insecure design: missing threat modelling and security requirements.
- Security misconfiguration: default accounts, verbose errors, open storage, missing headers.
- Vulnerable and outdated components: dependencies with known flaws.
- Identification and authentication failures: weak passwords, broken sessions.
- Software and data integrity failures: unsigned updates, unsafe deserialisation, compromised pipelines.
- Security logging and monitoring failures: attacks that go unnoticed.
- Server-side request forgery: the server fetches attacker-chosen URLs.
How to answer any security question
Use a three-part pattern: what the flaw is and why it works, a minimal example, and the fix at the right layer. Prefer fixes that remove the class of bug, such as parameterised queries and framework auto-escaping, over fixes that filter bad input. Mention defence in depth, where several independent controls limit the damage if one fails.
Web Security and OWASP Interview Questions and Answers: questions with worked answers
1 What is SQL injection and how do you prevent it?
easyIt happens when untrusted input becomes part of a SQL statement, so the input can change the query logic, for example making a WHERE clause always true. Prevent it with parameterised queries or prepared statements, where the database receives the query and values separately, and with an ORM used correctly. Whitelist anything that cannot be a parameter, like sort columns, and give the database account minimal privileges.
java// vulnerable: "SELECT * FROM users WHERE email = '" + email + "'" PreparedStatement ps = conn.prepareStatement("SELECT id, name FROM users WHERE email = ?"); ps.setString(1, email); ResultSet rs = ps.executeQuery();2 What is cross-site scripting and what are its types?
easyXSS lets an attacker run script in another user's browser in your site's origin, so it can read the page, act as the user and, if tokens are exposed, steal sessions. Stored XSS saves the payload on the server, for example in a comment. Reflected XSS echoes it from a request, and DOM-based XSS happens entirely in client code when untrusted data reaches a dangerous sink such as innerHTML. Fix by contextual output encoding, which frameworks do by default.
3 How do you prevent XSS in practice?
mediumRely on framework escaping and avoid raw HTML sinks such as innerHTML, document.write and dangerouslySetInnerHTML. When rich text is required, sanitise with a vetted library like DOMPurify. Add a strict Content Security Policy as a second layer, mark session cookies HttpOnly, and validate URLs so javascript: schemes are rejected. Encoding depends on context: HTML body, attribute, JavaScript and URL each need different encoding.
javascript// unsafe el.innerHTML = userComment; // safe for text el.textContent = userComment; // safe for limited HTML el.innerHTML = DOMPurify.sanitize(userHtml);4 What is a Content Security Policy?
mediumCSP is a response header that tells the browser which sources of scripts, styles, images and frames are allowed, so injected inline scripts or scripts from unknown origins do not run. A strong policy uses nonces or hashes with strict-dynamic instead of long allow-lists, forbids unsafe-inline for scripts, and sets object-src none and base-uri. Roll it out with Content-Security-Policy-Report-Only first.
textContent-Security-Policy: default-src 'self'; script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'5 What is CSRF and how is it prevented?
mediumCross-site request forgery makes a logged-in user's browser send an unwanted state-changing request, because the browser attaches cookies automatically. Prevent it with SameSite=Lax or Strict cookies, anti-CSRF tokens tied to the session and verified on unsafe methods, and checking the Origin header. Use POST and not GET for changes. APIs that authenticate by a header token, not a cookie, are not CSRF-prone, though they must protect that token from XSS.
6 What is broken access control and what is an IDOR?
mediumIt means the server does not enforce who may do what. An insecure direct object reference is the common case: GET /invoices/1042 returns the invoice of whoever asks, because the code checks that the user is logged in but not that the invoice belongs to them. Enforce authorisation on the server for every request, scope queries by the current user, deny by default, and test with two different accounts. Hiding buttons in the UI is not a control.
python# vulnerable invoice = Invoice.objects.get(pk=invoice_id) # fixed: scope by owner, return 404 when not theirs invoice = get_object_or_404(Invoice, pk=invoice_id, owner=request.user)7 How should passwords be stored?
mediumNever store plaintext or fast hashes such as MD5 or plain SHA-256. Use a slow, salted, purpose-built password hashing function: Argon2id is the current recommendation, with bcrypt or scrypt as acceptable alternatives, tuned to take on the order of hundreds of milliseconds. Each hash has its own random salt, which libraries handle for you. Compare in constant time, rate limit login attempts and offer multi-factor authentication.
pythonfrom argon2 import PasswordHasher ph = PasswordHasher() stored = ph.hash(password) ph.verify(stored, attempt) # raises on mismatch8 What are common mistakes with JWTs?
mediumAccepting the none algorithm or not pinning the expected algorithm, using weak or hard-coded secrets, not checking exp, iss and aud claims, putting sensitive data in the payload which is only encoded, not encrypted, and storing tokens in localStorage where XSS can read them. Tokens also cannot be revoked easily before expiry, so keep access tokens short-lived with refresh token rotation. A server-side session is often simpler.
9 How do you secure cookies and sessions?
mediumSet HttpOnly so scripts cannot read the cookie, Secure so it only travels over HTTPS, and SameSite for CSRF protection. Generate session IDs with a cryptographically secure random source, regenerate the ID on login to stop session fixation, expire sessions on logout and after inactivity, and store them server-side. Use the __Host- prefix for tighter binding.
textSet-Cookie: __Host-sid=9f2c...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=360010 What is SSRF and how do you defend against it?
mediumServer-side request forgery makes your server fetch a URL chosen by the attacker, which can reach internal services or cloud metadata endpoints such as 169.254.169.254 that return credentials. Defend by avoiding user-supplied URLs where possible, using an allow-list of hosts, resolving the name and rejecting private, loopback and link-local addresses, not following redirects blindly, and using network egress rules and metadata service protections such as IMDSv2.
pythonimport ipaddress, socket from urllib.parse import urlparse def is_safe(url): host = urlparse(url).hostname ip = ipaddress.ip_address(socket.gethostbyname(host)) return not (ip.is_private or ip.is_loopback or ip.is_link_local)11 What security headers should a site send?
mediumStrict-Transport-Security forces HTTPS, Content-Security-Policy limits script sources, X-Content-Type-Options: nosniff stops MIME sniffing, Referrer-Policy limits referrer data, and frame-ancestors in CSP, or X-Frame-Options, prevents clickjacking. Permissions-Policy restricts browser features. Libraries such as helmet in Express set sensible defaults. Headers are defence in depth and do not replace fixing the underlying bugs.
12 What is CORS and is it a security feature for the server?
mediumCORS is a browser mechanism that relaxes the same-origin policy, letting a page read responses from another origin only if that server allows it. It protects users by stopping a malicious site reading their data from another site with their cookies. It does not protect the server from direct requests, since curl ignores it. Misconfigurations such as reflecting any Origin with credentials allowed expose user data. Allow-list exact origins.
13 How do you handle file uploads securely?
mediumLimit size and count, check the content type by inspecting the file, not just the extension or client header, generate a new random file name, store outside the web root or in object storage on a separate domain, and serve with a safe Content-Type and Content-Disposition. Scan for malware if files are shared, and never execute or include uploaded files. Image processing libraries should be kept updated.
14 What is mass assignment and how do you stop it?
hardIt happens when a framework binds all request fields to a model, so a client adds isAdmin: true or changes ownerId and the server saves it. Prevent it by binding to a dedicated input DTO or schema that lists allowed fields, using allow-lists such as strong parameters, and setting sensitive fields only on the server.
javascript// vulnerable: User.update(req.body) const { name, bio } = userUpdateSchema.parse(req.body); // only allowed fields await User.updateOne({ _id: req.user.id }, { name, bio });15 What is insecure deserialisation?
hardDeserialising untrusted data with a format that can instantiate arbitrary objects, such as Java native serialisation, Python pickle or some YAML loaders, can let an attacker trigger code execution through gadget chains. Use data-only formats such as JSON with schema validation, never unpickle untrusted data, use safe loaders like yaml.safe_load, and sign data that must round-trip through the client.
16 How do you manage vulnerable dependencies and supply-chain risk?
hardKeep a lockfile, run automated scanning such as npm audit, pip-audit or Dependabot in CI, and update regularly with tests. Prefer fewer, well-maintained dependencies, review install scripts, pin versions or hashes for builds, and restrict CI secrets. Generate an SBOM for visibility, and watch for typosquatted package names. Treat a build pipeline as production infrastructure.
17 How do you approach threat modelling a new feature?
hardDraw the data flow: actors, components, data stores and trust boundaries. For each element ask what can go wrong, using a framework such as STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. Rank by impact and likelihood, decide mitigations, and turn them into requirements and tests. Doing it at design time is cheaper than patching later and addresses the insecure design category.
18 What should logging and monitoring cover for security?
hardLog authentication events, access control failures, input validation failures, admin actions and high-value transactions with timestamp, user, source and outcome, in a central, tamper-resistant store. Never log passwords, tokens or full card numbers, and prevent log injection by encoding newlines. Alert on patterns such as repeated failed logins and have an incident response process. Without detection, a breach can last months.
19 Authentication or authorisation: what is the difference, and what is defence in depth?
hardAuthentication establishes who the user is. Authorisation decides what that user is allowed to do, and must be checked on every request, close to the data. Defence in depth stacks independent controls so one failure is not fatal: input validation, parameterised queries, least-privilege database accounts, network segmentation, security headers, monitoring and rate limiting.
Frequently asked questions
Do developers need to know the OWASP Top 10 for interviews?
Yes, at least the categories and one prevention technique for each. Injection, XSS, access control and authentication are asked most.
Is the OWASP Top 10 a standard or a checklist?
It is an awareness document listing the most critical risk categories, not a complete checklist. The ASVS is the detailed verification standard.
Where should I start learning web security?
Read the OWASP cheat sheets, practise on intentionally vulnerable apps such as OWASP Juice Shop, and review your own project for each category.
Is HTTPS enough to secure a website?
No. HTTPS protects data in transit. Application flaws such as injection, XSS and broken access control are independent of transport encryption.
Related guides
- Backend Developer Interview Questions and Answers
- Frontend Developer Interview Questions and Answers
- Full Stack Developer Interview Questions and Answers
- Node.js Interview Questions and Answers (Node 22)
- Spring Boot Interview Questions and Answers (Spring Boot 3)
- Django Interview Questions and Answers (Django 5)
- REST API Interview Questions and Answers
More in Role-wise Interview Questions by Job and Tech Stack
- A/B Testing Interview Questions and Answers
- Android Developer Interview Questions and Answers
- Angular Interview Questions and Answers (Angular 18 and Later)
- Ansible Interview Questions and Answers
- API Testing and Postman Interview Questions
- Automation Testing Interview Questions and Answers
- AWS Interview Questions and Answers
- Azure Interview Questions and Answers
- Backend Developer Interview Questions and Answers
- Business Analyst Interview Questions and Answers
- Cloud Engineer Interview Questions and Answers
- Computer Vision Interview Questions and Answers