Web Security Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does the CIA triad in information security stand for?
Correct answer: Confidentiality, Integrity, Availability
Confidentiality means only the right people see the data, integrity means it isn't changed without permission, and availability means the system works when needed. Most attacks hit at least one of the three.
2. A form checks in JavaScript that the age field is a number from 18 to 120. Is that enough to protect the server?
Correct answer: No: requests can skip the page, so the server must validate too
Client-side validation is for user experience. Anyone can send a request with curl or DevTools, so every rule that matters must be checked again on the server.
3. What is the OWASP Top 10?
Correct answer: A regularly updated list of top web application security risks
OWASP (Open Worldwide Application Security Project) publishes the Top 10 as an awareness document. Broken access control, injection and security misconfiguration are among the entries.
4. What does the principle of least privilege mean?
Correct answer: Everyone gets only the permissions needed for their job
If an account or key with minimal rights is compromised, the damage is limited. A database user for a read-only report, for example, shouldn't be able to drop tables.
5. What is defense in depth?
Correct answer: Independent layers, so one failure doesn't expose everything
Escaping output, a Content Security Policy and HttpOnly cookies each reduce XSS damage on their own. Together they cover cases where one layer has a bug.
6. Why is "security through obscurity" (for example, a secret admin URL) not real protection?
Correct answer: Hidden things get found, so a real access check is still needed
Obscurity can slow an attacker down, but it can't replace authentication and authorization. The admin page must check who is calling it.
7. What is a trust boundary?
Correct answer: Where data moves from a less trusted zone to a more trusted one
Everything that crosses a trust boundary has to be validated: request bodies, headers, cookies, files and data from third-party APIs.
8. Which data from the browser can the server trust without checking?
Correct answer: None of it: the client can change all of it
The client fully controls what it sends. Even a hidden
pricefield or arolecookie can be edited, so the server must rely on its own data and checks.9. What does HTTPS protect?
Correct answer: It encrypts traffic and confirms the server's identity
TLS gives confidentiality, integrity and server authentication on the network. It doesn't fix bugs in the application itself.
10. An HTTPS page loads a script over plain
http://. What happens in modern browsers?Correct answer: It's blocked as mixed content, as it could be modified in transit
An active resource loaded over HTTP could be swapped by anyone on the network, which would break the page's security. Browsers block it; some passive content is auto-upgraded to HTTPS.
11. What does the
Strict-Transport-Security(HSTS) header do?Correct answer: Tells the browser to use only HTTPS for this site for a set time
With HSTS the browser rewrites
http://tohttps://before sending anything, which closes the window for SSL stripping attacks on later visits.12. Why should a login form never be served over plain HTTP?
Correct answer: Anyone on the same network could read or change the password
Without TLS every byte travels in clear text. An attacker in the middle can capture credentials or inject a fake form.
13. What does the padlock icon in the address bar guarantee?
Correct answer: Only that the connection to this domain is encrypted
Phishing sites can get valid certificates too. The padlock says nothing about who runs the site or whether its code is secure.
14. What is a secure context in the browser?
Correct answer: A page on HTTPS or localhost, where powerful APIs are allowed
Many APIs require a secure context because a network attacker could otherwise abuse them.
window.isSecureContexttells you if the current page qualifies.15. Why do browsers show a full-page warning for an invalid or self-signed certificate?
Correct answer: It can't confirm the real server, so traffic could be intercepted
A certificate binds a domain to a key, signed by a trusted authority. Clicking through the warning removes the protection HTTPS is supposed to give.
16. What is cross-site scripting (XSS)?
Correct answer: Injecting script that runs in other users' browsers on your site
The injected script runs with the site's origin: it can read the page, act as the user and send data to the attacker.
17. What is stored XSS?
Correct answer: The script is saved on the server and served to every viewer
Stored XSS is especially dangerous because victims only need to open a normal page, and it can affect many users at once.
18. What is reflected XSS?
Correct answer: Request input is echoed into the page without escaping
The attacker sends the victim a crafted link like
/search?q=<script>.... The server puts the value straight into the HTML, and the script runs.19. What is DOM-based XSS?
Correct answer: Client code writes data from a source into a sink like
innerHTMLThe server may never see the payload: everything happens in the browser's own JavaScript. That's why DOM XSS needs reviews of front-end code.
20. Which line safely shows a user's name in an element?
const name = new URLSearchParams(location.search).get('name');Correct answer:
el.textContent = name;textContenttreats the value as plain text.innerHTMLandouterHTMLparse it as HTML, so<img src=x onerror=...>would run code.21. Why is rendering
{comment.text}in JSX safe from XSS by default?Correct answer: React escapes strings before inserting them
React sets text through the DOM as text nodes. Markup in the string is shown literally instead of being parsed.
22. What risk does
dangerouslySetInnerHTMLbring in React?Correct answer: It inserts raw HTML, so user content can execute scripts
The long name is a warning. If the HTML comes from users or third parties, sanitize it first, for example with DOMPurify.
23. Why can
<a href={user.website}>in React still lead to XSS?Correct answer: A
javascript:URL runs code when clickedEscaping protects against breaking out of the attribute, but
javascript:is a valid URL scheme. Validate the protocol before using user-supplied links.24. What does an HTML sanitizer such as DOMPurify do?
Correct answer: It removes dangerous elements and keeps safe formatting
When you really need user HTML (a rich-text editor, for example), a well-maintained sanitizer strips
<script>, event handlers likeonerrorand dangerous URLs.25. What is output encoding (escaping) in the context of XSS?
Correct answer: Converting special characters into safe forms for that context
HTML body, attribute, URL and JavaScript contexts each need different encoding. Templating engines and frameworks do this automatically when used the normal way.
26. An attacker got XSS on your site. What can their script typically do?
Correct answer: Anything the user can do on that page, acting as them
The script runs as your site. Even without stealing cookies it can call your APIs with the user's session or show a fake login form.
27. Which approach to blocking XSS is the most reliable?
Correct answer: Encode output by context and sanitize HTML
Blocklists are easy to bypass:
<img onerror>,<svg onload>and encoding tricks don't contain<script>. Contextual encoding works no matter what the input is.28. What is cross-site request forgery (CSRF)?
Correct answer: Another site makes the victim's browser send a request with cookies
The attacker can't read the response, but the request itself (a transfer or a password change) runs as the logged-in user.
29. Why is CSRF possible with cookie-based sessions?
Correct answer: Browsers used to attach cookies whichever site started the request
Ambient credentials are the core of CSRF. The
SameSiteattribute was added to cookies to limit this behavior.30. What is a CSRF token?
Correct answer: A random secret that the server puts in forms and then checks
A forged request from another site doesn't include the right token, so the server rejects it. The token must be unpredictable and tied to the session.
31. Why must a GET request never change data (for example
GET /delete?id=5)?Correct answer: An
<img>tag, a link or a prefetcher can trigger a GETSafe methods like GET should only read. State changes belong in POST, PUT, PATCH or DELETE with CSRF protection.
32. What does
SameSite=Laxon a session cookie do?Correct answer: The cookie goes cross-site only on top-level navigations
With
Lax, a form POST from another site arrives without the cookie, which blocks classic CSRF. Modern browsers useLaxby default when the attribute is missing.33. How is
SameSite=Strictdifferent fromLax?Correct answer:
Strictwithholds the cookie even on links from other sitesWith
Strict, a user arriving from an email link looks logged out on the first page. That's whyLaxis a common default for session cookies.34. Does a CSRF attacker see the response to the forged request?
Correct answer: No: the same-origin policy stops it from reading the result
CSRF is about side effects, not reading data. That's why it targets actions like changing an email, not fetching a profile.
35. Which attack does a CSRF token NOT protect against?
Correct answer: XSS on the same site, as a script can read the token
Code running on your own origin can read your pages and tokens. XSS defeats CSRF defenses, so both have to be fixed.
36. Which parts make up the origin of a URL?
Correct answer: Scheme, host and port
https://shop.comandhttp://shop.comare different origins, and so arehttps://shop.comandhttps://shop.com:8443. The path doesn't matter.37. Are
https://app.example.comandhttps://api.example.comthe same origin?Correct answer: No: the hosts differ, though they're the same site
Subdomains are separate origins. They are same-site, which matters for cookies and
SameSite, but not for the same-origin policy.38. What does the same-origin policy stop?
Correct answer: One origin reading another origin's responses and DOM
Cross-origin images, scripts and form submissions are allowed. What's blocked by default is reading the response, such as the body of a
fetchto another origin.39. What is CORS?
Correct answer: A way for servers to say which origins may read responses
Cross-Origin Resource Sharing relaxes the same-origin policy through response headers like
Access-Control-Allow-Origin. It is enforced by the browser.40.
fetch('https://api.other.com/data')fails with a CORS error. Where is it fixed?Correct answer: On the
api.other.comserver, withAccess-Control-Allow-*headersOnly the resource owner can allow cross-origin reads.
no-corsgives an opaque response that JavaScript can't read.41. Does CORS protect your API from attackers using curl or a script on their own server?
Correct answer: No: only browsers enforce CORS, so the API needs real auth
CORS protects users' browsers from other websites reading data with their credentials. Non-browser clients ignore it completely.
42. What is a CORS preflight request?
Correct answer: An
OPTIONSrequest asking if the real cross-origin request is allowedRequests with methods like
PUTor headers likeContent-Type: application/jsontrigger a preflight. If the server's answer doesn't allow it, the real request isn't sent.43. Why can't a server respond with
Access-Control-Allow-Origin: *together withAccess-Control-Allow-Credentials: true?Correct answer: Otherwise any site could read responses sent with the user's cookies
With credentials the server has to name the exact allowed origin. It should check the
Originagainst an allowlist, not just echo it back.44. What is the difference between CORS and CSRF?
Correct answer: CORS controls who reads responses; CSRF is an attack sending requests
Simple form POSTs are sent cross-origin without any CORS check, so CORS settings alone don't stop CSRF.
45. What does the
HttpOnlycookie attribute do?Correct answer: JavaScript can't read the cookie, but requests still carry it
An XSS script can't steal an
HttpOnlysession cookie. It can still send requests that use it, soHttpOnlylimits damage rather than preventing XSS.46. What does the
Securecookie attribute do?Correct answer: The browser sends the cookie only over HTTPS
Without
Secure, a session cookie could leak over an accidental HTTP request. Session cookies should always beSecure.47. Which
Set-Cookieline is the best choice for a session cookie?Correct answer:
Set-Cookie: sid=...; Secure; HttpOnly; SameSite=Lax; Path=/Securekeeps it on HTTPS,HttpOnlyhides it from scripts andSameSite=Laxblocks most cross-site sends.48. Why is storing an access token in
localStoragerisky?Correct answer: Any script on the page, including XSS, can read and send it
localStoragehas noHttpOnlyequivalent. With XSS, a stolen token can be used from the attacker's machine until it expires.49. Which data should never be stored in
localStorage?Correct answer: Passwords, long-lived tokens and other secrets
localStorageis plain text, persistent and readable by any script on the origin. It's fine for preferences, not for secrets.50. What is a session ID, and what must it be like?
Correct answer: A long, random identifier that the server links to a user
If session IDs can be guessed, an attacker can take over sessions. Use the framework's generator, which relies on a cryptographically secure random source.
51. What should happen to the session when the user logs out?
Correct answer: The server invalidates it, so a copied ID stops working
Deleting the cookie on the client isn't enough: a stolen copy would still be valid. The server-side session must be destroyed.
52. Why should a new session ID be issued right after login?
Correct answer: To prevent session fixation with a pre-planted session ID
If the ID stays the same before and after login, an attacker who set it in advance would share the victim's logged-in session.
53. What is the difference between authentication and authorization?
Correct answer: Authentication checks who you are; authorization, what you may do
Logging in is authentication. Checking that you can edit this specific order is authorization, and it has to happen on every request.
54. How should passwords be stored in a database?
Correct answer: Hashed with a slow password algorithm like Argon2id and a salt
Fast hashes can be brute-forced at billions of guesses per second. Password hashing algorithms are slow by design and include salts against precomputed tables.
55. What is a salt in password hashing?
Correct answer: A random value per hash, so equal passwords hash differently
Salts make rainbow tables useless and stop attackers from cracking all users with the same password at once. Modern algorithms add salts automatically.
56. Why should a login form say "Invalid email or password" instead of "This email doesn't exist"?
Correct answer: A specific message reveals which accounts exist
Knowing which emails are registered helps credential stuffing and phishing. Keep messages and response times similar for both cases.
57. What is multi-factor authentication (MFA)?
Correct answer: Requiring two or more different kinds of proof
Factors are something you know, have or are. A stolen password alone isn't enough when a second factor is required.
58. What is credential stuffing?
Correct answer: Trying pairs leaked from other sites, hoping users reused them
Defenses include MFA, rate limiting, bot detection and checking new passwords against known breached lists.
59. Which measure helps most against brute-force login attempts?
Correct answer: Rate limiting and temporary lockouts after repeated failures
Limiting attempts per account and per IP makes guessing slow and noisy. Frequent forced password changes tend to make passwords weaker.
60. What does modern guidance (for example NIST) say about password rules?
Correct answer: Prefer long passwords and check them against breached lists
Rules like "one digit, one symbol" lead to predictable patterns. Length and blocking known leaked passwords are more effective.
61. How should a "Forgot password" link work?
Correct answer: Email a single-use, short-lived random token
If the site can email your current password, it stores it in a recoverable form. Reset tokens must be unguessable and expire quickly.
62. What is a passkey?
Correct answer: A key-pair login whose private key stays on the device
Passkeys use WebAuthn. The site keeps only the public key, and the signature is bound to the site's domain, which makes them resistant to phishing.
63. What is a Content Security Policy (CSP)?
Correct answer: A response header listing the allowed sources of resources
If an attacker injects a script that doesn't match the policy, the browser refuses to run it. CSP is a strong second layer against XSS.
64. With
Content-Security-Policy: script-src 'self', what happens to<script>alert(1)</script>written into the page?Correct answer: It doesn't run: inline scripts need a nonce or hash
Blocking inline scripts is what makes CSP useful against XSS. Inline event handlers like
onclickare blocked too.65. What does the
default-srcdirective do?Correct answer: It's the fallback for resource types with no directive of their own
A policy often starts with
default-src 'self'and then opens specific types, for exampleimg-src 'self' https://cdn.example.com.66. What is
Content-Security-Policy-Report-Onlyused for?Correct answer: Testing a policy: violations are reported, not blocked
Rolling out CSP in report-only mode first shows what would break, so you can fix legitimate scripts before enforcing.
67. Why does adding
'unsafe-inline'toscript-srcweaken CSP so much?Correct answer: It allows any inline script, which is what most XSS payloads are
With
'unsafe-inline'an injected<script>oronerrorhandler runs again. Nonces or hashes allow your own inline code without opening that door.68. What is clickjacking?
Correct answer: An invisible iframe of your site tricks users into clicking it
The victim thinks they're clicking "Play" but actually press "Delete account" on your site, which is loaded with their session.
69. How do you stop other sites from framing your pages?
Correct answer: Send CSP
frame-ancestors 'none'orX-Frame-Options: DENYframe-ancestorsis the modern standard.X-Frame-Optionsis the older header with the same purpose.70. A React app needs a payment provider's secret API key. Where should it live?
Correct answer: Only on the server, behind your own backend
Everything shipped to the browser can be read in DevTools. Only public keys (like a publishable key) can be in front-end code.
71. In Next.js, which environment variables end up in the browser bundle?
Correct answer: Only those with the
NEXT_PUBLIC_prefixNEXT_PUBLIC_variables are inlined at build time and become public. Secrets must not have this prefix and must be used only in server code.72. You accidentally pushed a real API key to a public Git repository. What is the right first step?
Correct answer: Revoke or rotate the key at the provider immediately
Bots scan public repositories for keys within minutes. Rewriting history doesn't help if the key was already copied, so it must be invalidated.
73. What does
npm auditdo?Correct answer: Checks dependencies against a known-vulnerability database
It reports known CVEs in your dependency tree and suggests fixed versions. It can't detect new or hidden malicious code.
74. Why should the lockfile (
package-lock.json) be committed and installed withnpm ciin CI?Correct answer: So every build gets exactly the same reviewed versions
Without a lockfile, a version range can pull a freshly published malicious release.
npm cifails if the lockfile andpackage.jsondisagree.75. Why are detailed error messages with stack traces dangerous in production?
Correct answer: They reveal internals like file paths and library versions
Show users a generic message with an error ID, and log the details on the server where only the team can see them.