Web Security Middle 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. 1. A value is HTML-escaped and then placed into an inline script: <script>var q = '{{value}}';</script>. Why is this still unsafe?

    Correct answer: A JS string context needs JS encoding, not HTML escaping

    Each context has its own escaping rules. The safest option is to avoid it: put data in a data- attribute or a JSON block and read it from your script.

  2. 2. Which of these is a DOM XSS sink?

    Correct answer: element.insertAdjacentHTML()

    Sinks parse strings as HTML or code: innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, setTimeout(string) and URL properties that accept javascript:.

  3. 3. Which of these is a typical DOM XSS source?

    Correct answer: location.hash

    Sources are values an attacker can control: the URL (location, hash, search), document.referrer, postMessage data and stored values from other users.

  4. 4. Why is eval(userInput) or new Function(userInput) always dangerous?

    Correct answer: It runs any string as code with the page's privileges

    If any part of the string comes from users, they control the code. Strict CSP also blocks these calls unless 'unsafe-eval' is set.

  5. 5. Where does Vue's v-html stand in terms of XSS?

    Correct answer: It renders raw HTML, so it must get sanitized content only

    Mustache {{ }} bindings escape text. v-html bypasses that on purpose and is the usual source of XSS in Vue apps.

  6. 6. What does Angular's bypassSecurityTrustHtml() do?

    Correct answer: Marks a value as trusted, skipping Angular's sanitization

    Angular sanitizes values bound to [innerHTML] by default. Bypass methods should be rare and applied only to content you fully control.

  7. 7. Users can upload SVG avatars that are served from your main domain. What's the risk?

    Correct answer: SVG can contain scripts that run on your origin as stored XSS

    Serve uploads from a separate domain, sanitize or rasterize SVGs, and send Content-Disposition: attachment or a strict CSP for user files.

  8. 8. Your app renders user-written Markdown to HTML. What must happen before inserting the result into the page?

    Correct answer: Sanitize the HTML, as Markdown can carry raw HTML and bad links

    Markdown is a superset that often passes HTML through. Disable raw HTML in the renderer and run the output through a sanitizer.

  9. 9. Why is "sanitize on input, store the clean version" less reliable than encoding on output?

    Correct answer: The same data can land in contexts needing different encoding

    Validate input for format, but encode at the point of output for the exact context. That works even for data that arrived through other channels.

  10. 10. What do Trusted Types add on top of normal XSS defenses?

    Correct answer: Sinks like innerHTML accept only objects from approved policies

    Enabled with require-trusted-types-for 'script' in CSP, they turn DOM XSS into a type error and force all HTML through a few reviewed places.

  11. 11. An app writes a user's display name into an attribute without quotes: <div title={{name}}>. What makes this worse than a quoted attribute?

    Correct answer: A space ends the attribute, so new ones like onmouseover can follow

    Unquoted attributes can be broken by many characters. Always quote attributes and use attribute encoding.

  12. 12. Server-rendered state is embedded like this: <script>window.__STATE__ = ${JSON.stringify(state)}</script>. What's the problem?

    Correct answer: A </script> in a string closes the tag early, allowing XSS

    The HTML parser sees </script> before JavaScript runs. Frameworks and serializers that are made for this escape <, > and /.

  13. 13. How does a nonce-based CSP work?

    Correct answer: The server adds a random per-response value to header and scripts

    An injected script doesn't know this response's nonce, so it's blocked. A nonce that never changes gives no protection.

  14. 14. What is a hash-based CSP source like 'sha256-...'?

    Correct answer: It allows one specific inline script whose content matches the hash

    Hashes suit static pages where the inline code doesn't change. Any change to the script means the hash must be updated.

  15. 15. What does 'strict-dynamic' do in script-src?

    Correct answer: Scripts loaded by a trusted script are trusted too

    This makes strict CSP practical with bundlers and loaders that add scripts at runtime, without long domain lists.

  16. 16. Why is a CSP like script-src 'self' https://cdn.example.com https://www.google.com considered weak?

    Correct answer: Allowed hosts often serve JSONP or old libraries that run code

    Research showed most allowlist policies can be bypassed this way. Nonces or hashes with 'strict-dynamic' are the recommended approach.

  17. 17. What does object-src 'none' protect against?

    Correct answer: Plugin content like <object> and <embed>

    It's part of every recommended strict policy, along with base-uri 'none' or 'self'.

  18. 18. Why should a strict CSP include base-uri 'none' (or 'self')?

    Correct answer: An injected <base href> could redirect relative script URLs

    A <base> tag changes how every relative URL resolves. Restricting it closes a bypass even when nonces are in place.

  19. 19. Which CSP directive limits where fetch, XHR and WebSocket connections can go?

    Correct answer: connect-src

    connect-src makes it harder for injected code to send data to an attacker's server, although other channels like images still exist.

  20. 20. Is a CSP set in a <meta http-equiv> tag the same as one in a response header?

    Correct answer: Mostly, but frame-ancestors and reporting need the header

    The meta tag also applies only after it's parsed. For full control, send CSP as an HTTP header.

  21. 21. In Next.js, how is a nonce-based CSP usually set up?

    Correct answer: A proxy makes a nonce per request; Next.js adds it to its scripts

    A per-request nonce means pages are rendered dynamically. Static pages can use hashes or a less strict policy instead.

  22. 22. How do you collect CSP violation reports?

    Correct answer: With report-to or the older report-uri directive

    Reports show which resources were blocked and on which page. Browser extensions create noise, so filter before alerting.

  23. 23. Does SameSite=Lax fully replace CSRF tokens?

    Correct answer: Not always: state-changing GETs and sibling subdomains remain

    SameSite is defense in depth. Sensitive actions still benefit from tokens or origin checks, especially when subdomains aren't all trusted.

  24. 24. What is the double-submit cookie pattern?

    Correct answer: The same random value goes in a cookie and a header, then is compared

    Another site can make the browser send the cookie but can't read it to copy into the header. The signed variant ties the value to the session.

  25. 25. How can checking the Origin header help against CSRF?

    Correct answer: Browsers set it, so unknown origins can be rejected

    Browser JavaScript can't forge Origin. Treat a missing header carefully, and combine the check with SameSite cookies or tokens.

  26. 26. What does the Sec-Fetch-Site request header tell the server?

    Correct answer: Where the request came from: same origin, same site or another site

    Fetch Metadata headers let a server apply a resource isolation policy, for example rejecting cross-site requests to API endpoints.

  27. 27. An API accepts only Content-Type: application/json. Why does that make classic CSRF harder?

    Correct answer: Forms can't send that type, and fetch with it needs a preflight

    This only holds if the server really rejects other content types. Some frameworks parse form bodies as JSON anyway, which reopens the hole.

  28. 28. What is login CSRF?

    Correct answer: The victim gets logged into the attacker's account unknowingly

    For example, the victim saves a credit card or search history into the attacker's account. Login forms need CSRF protection too.

  29. 29. An app authenticates API calls with an Authorization: Bearer header taken from memory, not cookies. Is CSRF a concern?

    Correct answer: Much less: browsers don't attach that header automatically

    CSRF needs ambient credentials. The trade-off is that the token is reachable by JavaScript, so XSS becomes the bigger risk.

  30. 30. Why should CSRF tokens not be put in URLs (for example ?csrf=...)?

    Correct answer: URLs leak through logs, history and the Referer header

    Keep tokens in hidden form fields or custom headers, where they don't end up in server logs or third-party referrers.

  31. 31. Why is reflecting any request Origin back in Access-Control-Allow-Origin with credentials dangerous?

    Correct answer: Any website can then read authenticated responses from your API

    It's the same as allowing every origin with credentials. Compare against an exact allowlist instead.

  32. 32. A server allows any origin that ends with example.com. What's the flaw?

    Correct answer: An attacker can register evil-example.com, which also matches

    Loose string checks and broken regexes are common CORS bugs. Parse the origin and compare the full host against a list.

  33. 33. Why should Access-Control-Allow-Origin: null never be allowed with credentials?

    Correct answer: Sandboxed iframes send Origin: null, so attackers can produce it

    Trusting null for local development often ends up in production and lets any page that makes a sandboxed iframe read your data.

  34. 34. When the response depends on the request Origin, which header should the server add?

    Correct answer: Vary: Origin

    Without Vary: Origin, a CDN or browser cache can serve a response with one origin's CORS headers to another origin.

  35. 35. What does Access-Control-Max-Age control?

    Correct answer: How long the browser may cache the preflight result

    A larger value means fewer preflights. Browsers cap it, so very large values don't have an effect.

  36. 36. By default, which response headers can front-end code read from a cross-origin response?

    Correct answer: Only safelisted ones; others need Access-Control-Expose-Headers

    For example, to read a custom X-Request-Id or Link header, the server must list it in Access-Control-Expose-Headers.

  37. 37. A fetch sends credentials: 'include' to another origin. What else is needed for the browser to expose the response?

    Correct answer: Access-Control-Allow-Credentials: true and an exact allowed origin

    Both headers are needed for credentialed requests. Also, third-party cookie restrictions may stop the cookies being sent at all.

  38. 38. Which request does NOT trigger a CORS preflight?

    Correct answer: A POST with a urlencoded form body and no custom headers

    Simple requests use GET, HEAD or POST with safelisted headers and content types. That's why servers can't rely on preflight to block form-like requests.

  39. 39. What are the three parts of a JWT?

    Correct answer: Header, payload and signature, separated by dots

    The header names the algorithm, the payload holds claims like sub and exp, and the signature lets the server check that nothing was changed.

  40. 40. Is the payload of a signed JWT (JWS) secret?

    Correct answer: No: it's only encoded, so any token holder can read it

    A signature protects integrity, not confidentiality. Don't put sensitive data in a JWT unless it's encrypted (JWE).

  41. 41. What must a server check when it receives a JWT?

    Correct answer: The signature with the expected key, plus exp, iss and aud

    Skipping any of these opens attacks: expired tokens still working, tokens for another service accepted, or forged signatures.

  42. 42. What is the alg: none attack on JWTs?

    Correct answer: A token with none and no signature gets accepted

    Always pin the allowed algorithms on the server instead of trusting the alg from the token header.

  43. 43. Why are JWTs harder to revoke than server-side sessions?

    Correct answer: No database lookup is made, so a stolen token works until expiry

    Common fixes are short-lived access tokens with refresh tokens, a token version per user, or a denylist checked on sensitive actions.

  44. 44. What is refresh token rotation?

    Correct answer: Each use issues a new refresh token and voids the old one

    If an old refresh token is used again, the server knows the token family was stolen and can revoke all of it.

  45. 45. Why are access tokens usually short-lived (minutes) while refresh tokens live longer?

    Correct answer: A leaked access token is useful only briefly

    Access tokens travel to many APIs and are easier to leak. Refresh tokens go only to the auth server, where they can be revoked.

  46. 46. What does the __Host- cookie name prefix guarantee?

    Correct answer: It was set with Secure, no Domain and Path=/

    Browsers reject __Host- cookies that don't meet these rules. That protects session cookies from being overwritten by a compromised subdomain.

  47. 47. Which session timeouts are recommended?

    Correct answer: An idle timeout plus an absolute lifetime, on the server

    Client-side timers can be bypassed. The server must reject expired sessions; sensitive apps use shorter timeouts.

  48. 48. Why should a user be asked for their password again before changing their email or password?

    Correct answer: So a hijacked or unattended session can't take over the account

    Re-authentication for critical actions limits the damage of session theft, CSRF and XSS.

  49. 49. Which OAuth 2.0 flow is recommended for a single-page app today?

    Correct answer: Authorization code flow with PKCE

    The implicit flow exposes tokens in URLs and history and is deprecated by the OAuth security best practices. PKCE protects the code exchange.

  50. 50. What problem does PKCE solve?

    Correct answer: A stolen code can't be used without the client's code_verifier

    The client sends a hash (code_challenge) at the start and the original value at the token step. An attacker who only saw the code can't finish the flow.

  51. 51. What is the state parameter in OAuth for?

    Correct answer: Linking the callback to this browser's request, preventing CSRF

    The client generates a random state, stores it, and checks it when the user comes back. PKCE also covers this, but state is still widely used.

  52. 52. Why must the authorization server match redirect_uri exactly against registered values?

    Correct answer: Loose matching lets attackers redirect codes to their own URL

    Prefix or wildcard matching has caused many real token leaks. Exact string matching is required by the security best practices.

  53. 53. What is the difference between an OIDC ID token and an OAuth access token?

    Correct answer: The ID token says who the user is; the access token calls APIs

    APIs shouldn't accept ID tokens as access tokens: the audience is the client, not the API.

  54. 54. What are OAuth scopes?

    Correct answer: Permissions a client requests, limiting what its token can do

    Request the smallest set of scopes the feature needs. Users are more likely to approve, and leaked tokens do less damage.

  55. 55. Why shouldn't a browser app hold an OAuth client secret?

    Correct answer: Anything in the browser is public, so a SPA relies on PKCE

    Confidential clients run on a server. If a SPA needs that level, a backend-for-frontend can hold the secret and the tokens.

  56. 56. "Sign in with Google" returns an ID token to your backend. What must the backend check?

    Correct answer: The signature with Google's keys, plus iss, aud and exp

    Without aud checking, a token issued for another app could log someone into yours.

  57. 57. What is IDOR (insecure direct object reference)?

    Correct answer: Changing an ID in a request exposes another user's data

    Random UUIDs make guessing harder but don't fix the bug. Every request must check that the current user may access that object.

  58. 58. An admin button is hidden in the UI for regular users. Is that access control?

    Correct answer: No: the API behind it must check the role

    UI hiding is only for user experience. Authorization belongs on the server for every endpoint.

  59. 59. What is mass assignment?

    Correct answer: Binding a request body to a model lets users set fields like isAdmin

    Accept only an allowlist of fields with a schema or DTO, and set sensitive fields on the server.

  60. 60. What is the difference between RBAC and ABAC?

    Correct answer: RBAC uses roles; ABAC uses attributes of user, resource and context

    "Editors can edit articles" is RBAC. "Editors can edit articles in their department during work hours" needs attributes.

  61. 61. Why is "deny by default" the safer authorization policy?

    Correct answer: A forgotten rule blocks access instead of allowing it

    New endpoints and fields appear all the time. Requiring an explicit allow rule means mistakes fail closed.

  62. 62. A multi-tenant SaaS filters data by tenantId from the request body. What's the risk?

    Correct answer: Users can change it; the tenant must come from the session

    Identity and tenant should be derived from the token or session on the server, never trusted from user input.

  63. 63. How do you prevent SQL injection?

    db.query("SELECT * FROM users WHERE email = '" + email + "'");

    Correct answer: With parameterized queries, like WHERE email = $1

    With parameters, the database receives the query and the data separately, so input can never change the query's structure.

  64. 64. What is NoSQL injection, for example in MongoDB?

    Correct answer: An object like { "$ne": null } in place of a string

    If password from JSON is used directly in find({ password }), an operator object bypasses the check. Validate types with a schema.

  65. 65. Which Node.js call is most dangerous with user input?

    Correct answer: exec('convert ' + fileName + ' out.png')

    exec passes the string to a shell, so ; rm -rf / in the name becomes a command. execFile with an argument array avoids the shell.

  66. 66. What is prototype pollution?

    Correct answer: Merging JSON with __proto__ keys changes Object.prototype

    A polluted prototype can change checks like if (user.isAdmin) everywhere. Use safe merge functions, Object.create(null) or Map, and schema validation.

  67. 67. How do you prevent path traversal in a file download endpoint?

    res.sendFile(path.join(UPLOADS, req.query.name));

    Correct answer: Resolve the final path and check it's inside UPLOADS

    ../../etc/passwd and encoded variants escape the folder. Checking the resolved absolute path or avoiding user paths entirely is reliable.

  68. 68. What is server-side template injection?

    Correct answer: User input gets evaluated as template code on the server

    Render user data as template variables, never by building template source from user strings. In many engines this leads to remote code execution.

  69. 69. What does X-Content-Type-Options: nosniff do?

    Correct answer: Stops the browser from guessing other than the declared type

    Without it, an uploaded file served as text/plain could be sniffed and run as HTML or JavaScript in some cases.

  70. 70. What is the risk the Referrer-Policy header reduces?

    Correct answer: Leaking full URLs with tokens or IDs to other sites

    strict-origin-when-cross-origin (the browser default) sends only the origin to other sites. Reset links with tokens still shouldn't link out.

  71. 71. What is Permissions-Policy used for?

    Correct answer: Turning off powerful browser features like camera for the page

    For example Permissions-Policy: camera=(), geolocation=() means even injected code or embedded ads can't request those features.

  72. 72. What does adding a site to the HSTS preload list achieve?

    Correct answer: Browsers use HTTPS for the domain even on the very first visit

    Preloading requires includeSubDomains and a long max-age. Removal is slow, so all subdomains must support HTTPS first.

  73. 73. What does Cross-Origin-Resource-Policy: same-origin do?

    Correct answer: Prevents other origins from embedding the resource

    CORP protects resources from being loaded into other sites' processes, which matters for side-channel attacks like Spectre.

  74. 74. A login page redirects to ?next= after success. How can that be abused?

    Correct answer: Open redirect: ?next=https://evil.com sends users to phishing

    Allow only relative paths or an allowlist of destinations, and watch out for tricks like //evil.com or /\evil.com.

  75. 75. What must a message event handler for postMessage check?

    window.addEventListener('message', (e) => {
      applySettings(e.data);
    });

    Correct answer: That e.origin is expected and e.data has the right shape

    Any window that holds a reference to yours can post messages. Without an origin check, another site can feed data into applySettings.