Security Interview Questions and Answers
27 questions8 beginner · 11 intermediate · 8 advancedLast reviewed
This set is for developers, DevOps engineers and anyone interviewing for a role where you build or run software that handles user data. It stays on the defensive side: how attacks work in principle, why they succeed, and the controls that stop them. You do not need to be a penetration tester to answer these well, but you do need to explain the reasoning behind each control.
Practise by answering each question aloud in under two minutes before you open the model answer. Aim for the same shape every time: name the risk, explain the mechanism, give the standard defence, then mention one trade-off or common mistake. Then try the follow-up. For the fundamentals, the cybersecurity course fills in the background.
1What is the CIA triad, and how would you apply it to a clinic's appointment system?Beginner
CIA stands for confidentiality, integrity and availability, the three properties a security design tries to protect. Confidentiality means only the right people can read data. Integrity means data cannot be changed without detection or authorisation. Availability means the system works when legitimate users need it.
For a clinic booking system: confidentiality covers patient names and visit reasons, so encrypt them and restrict who can query them. Integrity means a receptionist cannot silently alter a clinician's notes, so keep audit logs and validate input. Availability means the schedule stays reachable on a busy Monday, so think backups, redundancy and rate limiting. The properties often pull against each other, so you decide priorities per asset.
What the interviewer is checking: Whether you can turn an abstract acronym into concrete controls for a specific system.
Likely follow-up: Which of the three would you protect first for a public marketing site, and why?
2What is the difference between authentication and authorization?Beginner
Authentication answers "who are you?" and authorization answers "what are you allowed to do?". Authentication happens first: a password, a passkey or a one-time code proves identity. Authorization then decides, for that identity, whether this specific action on this specific resource is permitted.
A common bug is checking only one of them. A parcel-tracking API might confirm the caller is logged in but never check that the parcel belongs to them, so any user can read any record by changing an ID. Authorization must be enforced on the server for every request, not hidden behind a button in the UI. Roles, permissions and ownership checks all live in this layer.
What the interviewer is checking: Whether you separate identity from permission and know that authorization must be server-side.
Likely follow-up: Which comes first in a request pipeline, and what status codes do you return for each failure?
3Explain hashing, encryption and encoding. When would you use each?Beginner
Encoding changes representation so data travels safely, such as Base64 or URL encoding. It uses no secret and anyone can reverse it, so it provides no security. Encryption turns data into ciphertext using a key and is reversible by someone holding the right key; use it when you need the original back later. Hashing is a one-way function that produces a fixed-size digest; use it to check integrity or to store passwords, where you never need the original.
A frequent mistake is calling Base64 "encrypted" or storing passwords with reversible encryption. If an attacker gets the database and the key, every password is exposed.
python import base64, hashlib token = "user=42" print(base64.b64encode(token.encode()).decode()) print(base64.b64decode("dXNlcj00Mg==").decode()) print(hashlib.sha256(token.encode()).hexdigest()[:16])Output
dXNlcj00Mg== user=42 f4f27c0c2d8921bf
What the interviewer is checking: Clear vocabulary and the instinct that encoding is not a security control.
Likely follow-up: Is a plain SHA-256 of a password good enough to store? Why not?
4Why do we add a salt when hashing passwords?Beginner
A salt is a random value stored next to each user's hash and mixed in before hashing. It makes the same password produce a different hash for every user. Without salts, two users with the same password share a hash, and an attacker can use precomputed tables of common password hashes to reverse many accounts at once.
With a unique salt per user, precomputation is useless and the attacker must attack each account separately. The salt is not secret; it lives in the database with the hash. Salting alone does not make a fast hash safe, though. You still need a deliberately slow algorithm, which is the next layer of defence.
What the interviewer is checking: Understanding of what salting prevents and the fact that it is not a secret.
Likely follow-up: What is a pepper, and where would you store it?
5Compare symmetric and asymmetric encryption. Where is each used in practice?Beginner
Symmetric encryption uses one shared key for both encrypting and decrypting. It is fast, so it is used for bulk data: disk encryption, database fields and the traffic inside a TLS session. Its weakness is key distribution, because both sides must somehow share the key safely.
Asymmetric encryption uses a key pair: a public key anyone can have and a private key kept secret. It is much slower, but it solves distribution and enables digital signatures. Real systems combine them. TLS uses asymmetric techniques to agree on a fresh session key, then switches to symmetric encryption for the actual data. Signing uses the private key to sign and the public key to verify.
What the interviewer is checking: Whether you know the trade-off and the hybrid pattern real protocols use.
Likely follow-up: How does a digital signature differ from encrypting a message with a public key?
6What is SQL injection, and what is the correct way to prevent it?Beginner
SQL injection happens when user input is concatenated into a query string, so the database cannot tell the developer's SQL from the user's data. The input gets interpreted as SQL syntax. The fix is parameterised queries, also called prepared statements: the SQL text is sent with placeholders and the values are bound separately, so they are always treated as data.
Input validation and least-privilege database accounts are useful extra layers, but they are not a substitute. Escaping by hand is fragile. ORMs help only if you do not build raw strings inside them. The demo below uses a harmless apostrophe in a surname to show the difference.
python import sqlite3 db = sqlite3.connect(":memory:") db.execute("CREATE TABLE parcels (id INTEGER PRIMARY KEY, owner TEXT, locker INTEGER)") db.executemany("INSERT INTO parcels (owner, locker) VALUES (?, ?)", [("Asha", 12), ("O'Brien", 31), ("Chen", 7)]) name = "O'Brien" try: db.execute("SELECT locker FROM parcels WHERE owner = '" + name + "'") except sqlite3.OperationalError as e: print("concatenated:", e) row = db.execute("SELECT locker FROM parcels WHERE owner = ?", (name,)).fetchone() print("parameterised:", row)Output
concatenated: near "Brien": syntax error parameterised: (31,)
What the interviewer is checking: Whether you give the real fix (parameterisation) rather than only "sanitise input".
Likely follow-up: Can you parameterise a table name or an ORDER BY column? What do you do instead?
7What does the principle of least privilege mean? Give an example from a deployment.Beginner
Least privilege means every user, service and process gets only the access it needs to do its job, and nothing more. It limits the damage when an account or component is compromised or misused by mistake.
In a deployment: the web app's database user should be able to read and write its own tables but not drop schemas or read other databases. A reporting job gets read-only access. A CI pipeline gets a token scoped to one repository and one environment, not an organisation-wide admin key. Review permissions periodically, because access tends to accumulate as people change teams. Short-lived credentials make this easier to maintain.
What the interviewer is checking: Practical application of the principle, not just the definition.
Likely follow-up: How would you retrofit least privilege onto a system where every service shares one admin credential?
8What does HTTPS actually protect, and what does it not protect?Beginner
HTTPS is HTTP over TLS. It gives you confidentiality and integrity in transit, so people on the network cannot read or alter requests, and it authenticates the server through its certificate so you know you reached the right host.
It does not protect the data once it arrives. A server with an injection bug, weak access control or a leaked database is still vulnerable. It does not hide which domain you connect to from the network, and it does not verify that a site is trustworthy, only that you are talking to whoever holds that certificate. Treat TLS as a necessary baseline, not a complete security story.
What the interviewer is checking: Realistic understanding of TLS scope and avoiding the "padlock means safe" myth.
Likely follow-up: What does HSTS add on top of redirecting HTTP to HTTPS?
9How should a modern application store user passwords?Intermediate
Never store the password or an encrypted copy. Store a salted hash made with a deliberately slow, memory-hard algorithm such as Argon2id, scrypt or bcrypt (PBKDF2 is acceptable where it is mandated). Slowness matters: if an attacker steals the table, each guess costs real time and memory, which limits offline cracking.
Generate a unique random salt per user, tune the cost so a login takes a noticeable fraction of a second on your hardware, and compare digests in constant time. Plan for upgrading parameters later by storing the algorithm and cost with each hash and re-hashing at next login. Add rate limiting, breached-password checks and MFA, since hashing only protects a stolen database.
python import hashlib, hmac, os def make_record(password: str) -> tuple[bytes, bytes]: salt = os.urandom(16) digest = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1) return salt, digest def check(password: str, salt: bytes, digest: bytes) -> bool: candidate = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1) return hmac.compare_digest(candidate, digest) salt, digest = make_record("tulip-ladder-9") print(check("tulip-ladder-9", salt, digest)) print(check("tulip-ladder-8", salt, digest)) print(len(digest))Output
True False 64
What the interviewer is checking: Knowing the current practice, including why slowness and constant-time comparison matter.
Likely follow-up: How would you migrate existing users from an old fast hash without forcing a password reset?
10Walk me through what happens in a TLS handshake, at a high level.Intermediate
The client says hello with the TLS versions and cipher suites it supports. The server picks one and sends its certificate. The client validates that certificate: it chains to a trusted certificate authority, is not expired, and matches the hostname.
Next, both sides run a key exchange, using ephemeral Diffie-Hellman in modern versions, to derive the same fresh session keys without ever sending them. Each side confirms the handshake was not tampered with, and from then on the traffic is encrypted with fast symmetric keys. Because the keys are ephemeral, recording the traffic and later stealing the server's long-term private key does not reveal past sessions; that property is forward secrecy. Mutual TLS adds a client certificate when the server must verify the caller too.
What the interviewer is checking: Whether you can sketch the flow and name the purpose of each step without drowning in detail.
Likely follow-up: What goes wrong if a client skips certificate validation to "make the error go away"?
11How do XSS and CSRF differ? Explain each in one or two sentences.Intermediate
Cross-site scripting (XSS) is when an attacker gets their script to run in your page, usually because the app puts untrusted data into HTML without proper output encoding. The script runs with your site's origin, so it can read the page, act as the user and talk to your APIs.
Cross-site request forgery (CSRF) is different: the attacker's page does not run code on your site but causes the victim's browser to send a request to it, and the browser attaches the victim's cookies automatically. The server then acts on a request the user never intended. The key contrast: XSS abuses the user's trust in the site's page, CSRF abuses the site's trust in the browser's cookies. XSS can also defeat CSRF defences, since injected script can read tokens.
What the interviewer is checking: Clean mental models of both attacks and the awareness that XSS undermines CSRF tokens.
Likely follow-up: If a site is fully protected against CSRF, can XSS still hurt it?
12How do you defend a web app against XSS?Intermediate
The primary defence is context-aware output encoding: encode untrusted data for the place it lands, whether HTML body, attribute, JavaScript or URL. Modern frameworks such as React escape text by default, so the risk concentrates where you bypass that, for example with raw HTML insertion properties. Avoid those, and when rich text is genuinely needed, run it through a maintained sanitiser with an allow-list.
Add defence in depth: a Content Security Policy that restricts script sources and blocks inline scripts, HttpOnly cookies so injected script cannot read session cookies, and input validation for shape (not as the main defence). Review dependencies that render user content. Treat each layer as a safety net for the others failing.
What the interviewer is checking: Priority order: encode on output first, then sanitise, then CSP and cookie flags as backup.
Likely follow-up: Why is blacklisting dangerous tags a poor sanitising strategy?
13How do you defend against CSRF? Which defences still matter now that browsers support SameSite cookies?Intermediate
Layer several controls. First, set session cookies with SameSite=Lax or Strict so browsers do not send them on most cross-site requests. Second, use anti-CSRF tokens: a per-session or per-request secret that state-changing requests must include, which a cross-site page cannot read. Third, never change state on GET requests.
SameSite is a strong default but not a full replacement. Behaviour differs on older browsers, and Lax still sends cookies on top-level navigations. Sites that are subdomains of each other count as same-site, so a compromised sibling subdomain can still matter. For APIs that use bearer tokens in headers rather than cookies, classic CSRF largely disappears, because the browser does not attach the header automatically. Checking Origin on sensitive requests is another useful layer.
What the interviewer is checking: Up-to-date knowledge that SameSite helps a lot but should not be the only layer.
Likely follow-up: Why is the double-submit cookie pattern weaker when a sibling subdomain is compromised?
14What is the same-origin policy, and what problem does CORS solve?Intermediate
An origin is scheme plus host plus port. The same-origin policy stops a page from one origin from reading responses from another, which prevents a random website from reading your mail in another tab. It restricts reading, not necessarily sending: the request may still reach the server.
CORS (cross-origin resource sharing) is how a server opts in to relaxing that rule for specific origins by returning headers such as Access-Control-Allow-Origin. A typical case is a front end on one domain calling an API on another. Browsers send a preflight OPTIONS request for non-simple requests first. Two points interviewers like: CORS is enforced by browsers only, so it does not protect your API from curl or other servers, and allowing credentials with a wildcard origin is not permitted.
What the interviewer is checking: Whether you understand CORS as a browser relaxation mechanism, not an authentication control.
Likely follow-up: A developer "fixes" a CORS error by reflecting any Origin header back. What is wrong with that?
15Should I keep sessions in server-side storage or use JWTs in the browser? What are the trade-offs?Intermediate
Server-side sessions store state on the server and give the client an opaque random ID in a cookie. Revoking is trivial: delete the record. The cost is a shared store such as a database or cache, which every instance needs to reach.
JWTs are self-contained and signed, so services can verify them without a lookup, which suits distributed systems. The downside is revocation: a token stays valid until it expires, so use short lifetimes, refresh tokens and a deny-list if you must cut off access early. Where you keep a token also matters; local storage is readable by any injected script, while an HttpOnly cookie is not. For a typical single web application, plain server-side sessions are often the simpler and safer choice. See the JWT course for detail.
What the interviewer is checking: Balanced judgement rather than "JWT is modern so use it".
Likely follow-up: How would you log a user out of every device immediately if you use JWTs?
16What cookie attributes and practices matter for secure session management?Intermediate
Generate the session ID with a cryptographically secure random source, long enough to be unguessable, and keep it opaque. Set the Secure flag so it travels only over HTTPS, HttpOnly so scripts cannot read it, and SameSite to limit cross-site sending. Scope it with a narrow Path and Domain.
Regenerate the session ID on login and on privilege change, which prevents session fixation. Expire sessions with both an idle timeout and an absolute lifetime, and invalidate them on the server at logout rather than just deleting the cookie. Re-authenticate before sensitive actions such as changing the email or payment details. Never put the session ID in a URL, where it leaks through logs and referrer headers.
What the interviewer is checking: Practical checklist knowledge, including fixation and server-side invalidation.
Likely follow-up: What is session fixation, and what single step on login defeats it?
17What is broken access control, and how would you find and fix an IDOR in an orders API?Intermediate
Broken access control means a user can act outside their intended permissions. An insecure direct object reference (IDOR) is the classic form: an endpoint like GET /orders/1042 returns the order for any logged-in caller who changes the number, because the server checks authentication but not ownership.
To find it during a review, take two test accounts and confirm that account A cannot read, edit or delete account B's objects through any endpoint, including list filters and bulk exports. The fix is to enforce authorization on the server in one central place: load the object scoped to the current user (WHERE id = ? AND customer_id = ?) or run a policy check before returning it. Unpredictable IDs are a mild extra, not the fix. Add automated tests so a new endpoint cannot forget the check.
What the interviewer is checking: Practical testing mindset and the principle that authorization is checked per object, per request.
Likely follow-up: How would you structure the code so a developer cannot forget the ownership check?
18What are security misconfiguration and vulnerable components, and how do you manage them in a project?Intermediate
Security misconfiguration covers insecure defaults and settings: debug mode in production, default admin accounts, open storage buckets, verbose error pages, unnecessary ports, missing security headers. Vulnerable components means shipping libraries, frameworks or base images with known flaws, often transitive dependencies nobody chose consciously.
Manage the first with infrastructure as code, hardened baseline configurations and automated checks, so environments are consistent and reviewable. Manage the second with an inventory of dependencies (a software bill of materials), automated dependency scanning in CI, lock files, and a routine for upgrading promptly. Remove what you do not use. Both categories sit in the OWASP Top 10 course and come from process gaps more than clever attacks.
What the interviewer is checking: Process thinking: automated detection and ownership, not one-off audits.
Likely follow-up: A critical CVE lands in a transitive dependency. What is your first hour?
19Where and how should an application keep secrets such as API keys and database passwords?Intermediate
Not in source code, container images or front-end bundles. Keep secrets in a dedicated secrets manager or the platform's secret store and inject them at runtime through environment variables or mounted files, with access limited to the workloads that need them. Separate secrets per environment so a leaked development key cannot touch production.
Add controls around them: audit logs of access, rotation on a schedule and after any suspected exposure, and short-lived credentials where possible, such as tokens issued to a service identity. Run secret scanning in CI and pre-commit hooks to catch accidents. Anything that reached a public repository must be treated as compromised and rotated, because deleting the commit does not undo exposure.
What the interviewer is checking: Awareness of the full lifecycle: storage, access, rotation and leak response.
Likely follow-up: How would you design rotation of a database password with zero downtime?
20A teammate says CORS protects our API from unauthorised callers. How do you respond?Advanced
I would explain that it does not. CORS is a browser rule about whether a web page's JavaScript may read a cross-origin response. A script, curl or another server ignores it completely, so it provides no authentication or authorisation.
Real protection comes from verifying credentials on each request and checking permissions on the server. CORS still matters for the narrow browser case: a misconfigured policy that trusts every origin while accepting cookies can let a malicious site read a logged-in user's data through their browser. So configure an explicit allow-list of origins, avoid reflecting arbitrary origins, and keep credentials mode deliberate. Treat CORS as protecting users' browsers, not your server.
What the interviewer is checking: Willingness to correct a common misconception politely and precisely.
Likely follow-up: What does a preflight request look like, and who decides whether to send it?
21What are the common mistakes teams make with JWT authentication?Advanced
The usual pitfalls: treating the payload as secret (it is only Base64-encoded, so anyone holding the token can read it); accepting the algorithm named in the token header instead of enforcing the expected one on the server; weak or hard-coded signing secrets; not validating exp, iss and aud; very long lifetimes with no revocation plan; and storing tokens in places scripts can read.
Safer practice: verify with a fixed algorithm and key, keep access tokens short-lived, rotate keys with a key ID, put minimal data in claims, and never store sensitive information in the payload. Prefer asymmetric signing when many services only need to verify. Decoding is not verifying, and the snippet shows how readable the payload is.
python import base64, json def part(segment: str) -> dict: segment += "=" * (-len(segment) % 4) return json.loads(base64.urlsafe_b64decode(segment)) def enc(d): return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode() token = enc({"alg": "HS256"}) + "." + enc({"sub": "42", "role": "viewer"}) + ".signature-goes-here" header, payload, _sig = token.split(".") print(part(payload))Output
{'sub': '42', 'role': 'viewer'}What the interviewer is checking: Depth beyond "JWTs are signed": verification rules, lifetime and storage.
Likely follow-up: Why would you choose RS256-style signing over a shared HMAC secret in a microservice setup?
22How would you run a threat modelling session for a new file-upload feature?Advanced
Start with a simple data-flow diagram: browser, API, storage, any scanner or processing worker, and the trust boundaries between them. Then walk each element and flow with a framework such as STRIDE (spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege) to list what could go wrong.
For uploads, the threats include oversized files exhausting storage, files with a misleading type, malware passed to other users, and one user reading another's files. For each threat, agree a mitigation or an explicit accepted risk: size limits, content-type checks by inspecting the content, storage outside the web root with random names, malware scanning, authorisation on download, and quotas. Record decisions, assign owners, and revisit when the design changes.
What the interviewer is checking: A structured method applied to a concrete feature, ending in prioritised, owned actions.
Likely follow-up: How do you decide which identified threats are worth fixing first?
23Design a secure password reset flow. What can go wrong with the obvious approach?Advanced
Generate a high-entropy, single-use reset token with a short expiry, store only its hash, and email a link containing it. Respond identically whether or not the email exists, so the form cannot be used to enumerate accounts. Rate limit requests per account and per IP.
On completing the reset, check the token, enforce the password policy, then invalidate the token, all existing sessions and, ideally, notify the user by email. Common mistakes: guessable tokens or ones built from timestamps, tokens that never expire, security questions as the only check, leaking tokens in referrer headers or logs, and trusting a host header when building the link. Offer MFA-aware recovery paths, since reset flows are an easy bypass of strong login controls.
What the interviewer is checking: Holistic design thinking, including enumeration, token handling and session invalidation.
Likely follow-up: How does account recovery interact with MFA, and who is the weakest link?
24What does defense in depth mean, and how does it apply to a three-tier web app?Advanced
Defense in depth means layering independent controls so that one failure does not mean a breach. No single control is perfect, so attackers must defeat several.
In a three-tier application: at the edge, TLS, a web application firewall and rate limiting; in the application, input validation, output encoding, authorisation checks and secure session handling; in the data tier, parameterised queries, least-privilege database accounts and encryption at rest. Around it all, network segmentation so the database is not internet-reachable, centralised logging with alerts, and patched components. The test is simple: if an injection bug slips through the code, does the restricted database account and segmentation still limit the damage?
What the interviewer is checking: Ability to place controls at each layer and reason about failure of one layer.
Likely follow-up: Give an example where adding more layers made the system worse.
25Our software supply chain worries the CTO. What practical steps reduce the risk from third-party packages?Advanced
Start with visibility: generate a software bill of materials and know every direct and transitive dependency. Pin versions with lock files and install from a controlled, preferably mirrored, registry. Scan continuously for known vulnerabilities and review upgrades rather than auto-merging blindly.
Reduce exposure: remove unused packages, prefer well-maintained libraries with several maintainers, and watch for lookalike names when adding packages. In CI, give build jobs minimal permissions and short-lived credentials, since a compromised pipeline can ship malicious code. Where available, verify signatures or provenance of artefacts, and build from clean, reproducible environments. Accept that you cannot review every line, so combine these controls with runtime monitoring and a rehearsed rollback.
What the interviewer is checking: Realistic, layered supply-chain controls and honest acknowledgement of residual risk.
Likely follow-up: How do you handle a dependency whose maintainer has abandoned it?
26Someone pushed a live cloud access key to a public repo an hour ago. What do you do?Advanced
Act on the key first, history second. Revoke or rotate the key immediately and replace it for legitimate workloads, because the moment it was public it must be assumed compromised. Rewriting git history does not help on its own, since copies and forks may already exist.
Then investigate: review the provider's audit logs for activity from that key since the push, check for new resources, users, roles or unusual billing, and remove anything unauthorised. Scope what the key could reach, which shows how bad it could be and demonstrates why least privilege matters. Finally, learn from it: add secret scanning and pre-commit checks, move to short-lived credentials, and write a short blameless report with follow-up actions.
What the interviewer is checking: Calm prioritisation: contain, investigate, then prevent, with no blame.
Likely follow-up: How would you detect this kind of leak automatically next time?
27Describe the main phases of incident response, and what you would do in the first hour of suspected data theft.Advanced
A common model is preparation, detection and analysis, containment, eradication, recovery and a post-incident review. Preparation is the part that pays off: an on-call rota, runbooks, logging you can trust, and agreed communication channels.
In the first hour: confirm it is real and open an incident channel with a clear commander; preserve evidence such as logs and snapshots before changing things; contain by isolating affected systems or revoking credentials in a way that does not destroy evidence; and start a timeline. Involve legal and communications early if personal data may be affected, since notification duties can apply. Afterwards, hold a blameless review with concrete fixes. Avoid common mistakes: wiping machines too soon, working in silence, or announcing conclusions before facts are known.
What the interviewer is checking: Structured calm under pressure, evidence preservation and cross-team coordination.
Likely follow-up: How do you decide between containing immediately and watching the attacker to learn more?
Fill the gaps with a free course
If one of these Security answers felt shaky, these 3 courses cover the same ground step by step: Cybersecurity Fundamentals, OWASP Top 10, JWT Authentication.
More interview questions
- Java
- Spring Boot
- Python
- JavaScript
- React
- Node.js
- C++
- Data Structures & Algorithms
- SQL & Databases
- System Design
- DevOps
- AWS & Cloud
- Generative AI & LLMs
- Machine Learning
- Behavioral & HR
Practising Security for a real opening? Upload your resume to see which open jobs list Security skills you already have, or browse open roles.