JavaScript Security Basics Quiz

JavaScript
0 Passed
0% acceptance

Test your knowledge with 40 questions on web security fundamentals—covering XSS types, prevention strategies, CSRF mechanics, and defense techniques like tokens, SameSite cookies, and Content Security Policy.

40 Questions
~80 minutes
1

Question 1

Why is client-side security important even when the server is secure?

A
Because attackers can manipulate the frontend to bypass server checks or steal data
B
Because browsers ignore server responses
C
Because JavaScript runs faster than backend code
D
Because servers cannot validate user input
2

Question 2

What is the principle of “defense in depth” in web security?

A
Using multiple overlapping security controls to protect against failure of any single layer
B
Encrypting all JavaScript files
C
Blocking all third-party scripts
D
Disabling cookies entirely
3

Question 3

Which of the following is a common goal of client-side attacks?

A
Steal session cookies or authentication tokens
B
Increase server CPU usage
C
Compress HTML files
D
Improve SEO ranking
4

Question 4

What role does the Same-Origin Policy (SOP) play in browser security?

A
It restricts scripts from one origin from reading data from another origin
B
It prevents all JavaScript execution
C
It encrypts localStorage data
D
It disables network requests
5

Question 5

What is Cross-Site Scripting (XSS)?

A
An attack where malicious scripts are injected and executed in a victim’s browser
B
A method to compress JavaScript files
C
A way to authenticate users across domains
D
A browser rendering bug
6

Question 6

Why is XSS dangerous?

A
It can steal cookies, session tokens, or perform actions as the user
B
It slows down the browser
C
It increases bandwidth usage
D
It breaks CSS layouts
7

Question 7

What enables an XSS attack to succeed?

A
Untrusted data rendered in the DOM without proper escaping or sanitization
B
Using HTTPS
C
Minifying JavaScript
D
Disabling JavaScript
8

Question 8

Which built-in browser feature can help mitigate some XSS impacts?

A
HttpOnly cookies
B
localStorage
C
console.log()
D
Web Workers
9

Question 9

What characterizes a reflected XSS attack?

A
Malicious script is embedded in a URL and reflected off the server in the response
B
Script is stored permanently in a database and served to all users
C
Attack occurs only in local files
D
It requires physical access to the server
10

Question 10

How does stored (persistent) XSS differ from reflected XSS?

A
Stored XSS saves malicious input on the server (e.g., in a comment) and affects multiple users
B
Stored XSS only affects the attacker
C
Reflected XSS is worse
D
Stored XSS cannot be mitigated
11

Question 11

What defines DOM-based XSS?

A
The vulnerability exists entirely in client-side code that modifies the DOM with untrusted data
B
It only occurs in XML documents
C
The server must be compromised
D
It requires WebAssembly
12

Question 12

Which code snippet shows a DOM-based XSS vulnerability?

javascript
// URL: https://example.com/#<script>alert(1)</script>
const hash = location.hash.substring(1);
document.body.innerHTML = hash;
A
Using innerHTML with location.hash without sanitization
B
Using console.log
C
Reading from localStorage
D
Calling fetch()
13

Question 13

In which type of XSS is the malicious payload never sent to the server?

A
DOM-based XSS
B
Stored XSS
C
Reflected XSS
D
All types send it to the server
14

Question 14

Which input source is commonly exploited in DOM-based XSS?

A
window.location
B
navigator.userAgent
C
performance.now()
D
document.title
15

Question 15

What is the most effective way to prevent XSS when inserting user data into HTML?

A
Context-aware output encoding (e.g., HTML-escape before inserting)
B
Using eval()
C
Disabling JavaScript
D
Minifying code
16

Question 16

Why is input validation alone insufficient to prevent XSS?

A
Because the same input may be safe in one context but dangerous in another
B
Because validation slows down the app
C
Because browsers ignore validation
D
Because validation removes all special characters
17

Question 17

Which method is safe for inserting user text into the DOM?

javascript
const userInput = '<img src=x onerror=alert(1)>';
// Which is secure?
A
element.textContent = userInput;
B
element.innerHTML = userInput;
C
document.write(userInput);
D
eval(userInput);
18

Question 18

What does this code do safely?

javascript
const div = document.createElement('div');
div.textContent = userInput;
container.appendChild(div);
A
Inserts userInput as plain text, preventing XSS
B
Executes userInput as JavaScript
C
Sends userInput to the server
D
Sanitizes userInput using regex
19

Question 19

What is the purpose of a Content Security Policy (CSP)?

A
To restrict which scripts, styles, and resources can be loaded and executed
B
To compress JavaScript files
C
To validate form inputs
D
To encrypt cookies
20

Question 20

Which CSP directive helps prevent inline script execution?

A
script-src 'self'
B
img-src *
C
default-src *
D
style-src unsafe-inline
21

Question 21

What is a safe alternative to using innerHTML with user data?

A
Create elements with DOM APIs and set textContent
B
Use eval
C
Replace all < characters with <' manually
D
Use innerHTML but add // comments
22

Question 22

Which library is commonly used to sanitize HTML and prevent XSS?

A
DOMPurify
B
jQuery
C
Lodash
D
Axios
23

Question 23

What is Cross-Site Request Forgery (CSRF)?

A
An attack that tricks a user’s browser into making unauthorized requests to a site where they’re authenticated
B
A virus that infects JavaScript files
C
A method to bypass HTTPS
D
A type of SQL injection
24

Question 24

Why can CSRF succeed even on secure sites?

A
Because browsers automatically include cookies with same-site requests
B
Because servers ignore authentication
C
Because JavaScript is disabled
D
Because all APIs are public
25

Question 25

Which HTTP methods are most commonly targeted in CSRF attacks?

A
POST and state-changing GET requests
B
OPTIONS
C
HEAD
D
Only PUT
26

Question 26

Can a CSRF attack read the response from the forged request?

A
No, due to the Same-Origin Policy
B
Yes, always
C
Only if CORS is enabled
D
Only with WebSockets
27

Question 27

Which scenario is a classic CSRF example?

A
A malicious site submits a form to your bank’s transfer endpoint while you’re logged in
B
A user types a password incorrectly
C
A script logs console errors
D
An image fails to load
28

Question 28

What is the purpose of an anti-CSRF token?

A
To provide a secret value that an attacker cannot predict or access due to Same-Origin Policy
B
To encrypt form data
C
To replace cookies
D
To compress HTTP requests
29

Question 29

Where should an anti-CSRF token be included in a form?

A
As a hidden input field
B
In the action URL
C
In a CSS class
D
In the form’s enctype
30

Question 30

What does the SameSite cookie attribute do?

A
Prevents cookies from being sent in cross-site requests
B
Encrypts cookie values
C
Makes cookies expire faster
D
Disables JavaScript access to cookies
31

Question 31

Which SameSite value allows cookies on top-level navigations but blocks them in cross-site POSTs?

A
Lax
B
Strict
C
None
D
Auto
32

Question 32

What is the “double submit cookie” pattern?

A
Sending a random token in both a cookie and a request header/body and verifying they match
B
Submitting the same form twice
C
Using two different cookies for session
D
Requiring two-factor authentication
33

Question 33

Which code snippet shows a secure way to include a CSRF token in a fetch request?

javascript
// Assume csrfToken is rendered in a meta tag or global JS var
fetch('/transfer', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': csrfToken  // from trusted source
  },
  body: JSON.stringify({ to: 'attacker', amount: 100 })
})
A
Including the token in a custom header like X-CSRF-Token
B
Putting the token in the URL
C
Omitting the token entirely
D
Using eval to generate the token
34

Question 34

Why can’t an attacker read your CSRF token if it’s in a meta tag?

A
Because of the Same-Origin Policy—cross-origin scripts can’t read your page’s DOM
B
Because meta tags are encrypted
C
Because browsers block all scripts
D
Because tokens expire in 1ms
35

Question 35

What is a limitation of relying only on SameSite cookies for CSRF protection?

A
Older browsers may not support SameSite or may ignore it
B
SameSite breaks all forms
C
It only works with GET requests
D
It requires WebAssembly
36

Question 36

How should CSRF tokens be generated?

A
Using a cryptographically secure random value per user session
B
Using the user’s email as the token
C
Hardcoding "secret123" for all users
D
Incrementing a counter
37

Question 37

Which cookie attribute should accompany SameSite=None?

A
Secure
B
HttpOnly
C
Partitioned
D
Max-Age
38

Question 38

What is wrong with this form?

html
<form action="/delete-account" method="POST">
  <button type="submit">Delete</button>
</form>
A
It lacks a CSRF token, making it vulnerable to forged submissions
B
It uses POST instead of GET
C
It has no CSS
D
It uses a button
39

Question 39

Why is it unsafe to store a CSRF token in localStorage and send it in a header?

A
Because XSS can read localStorage, combining XSS + CSRF into a worse attack
B
Because localStorage is slower
C
Because headers can’t contain tokens
D
Because it increases cookie size
40

Question 40

Which combination provides strong CSRF protection?

A
Anti-CSRF tokens + SameSite=Lax cookies + avoiding state changes via GET
B
Only using HTTPS
C
Minifying JavaScript
D
Using base64 encoding

QUIZZES IN JavaScript