Express JS Express Security and Authentication 1 — Questions and Answers
Question 1: What is the primary purpose of JSON Web Tokens (JWT) in an Express application?
- Stateless authentication by encoding user identity in a signed token (Correct answer)
- Encrypting database connections
- Storing session data server-side
- Compressing JSON payloads
Correct answer: Stateless authentication by encoding user identity in a signed token
JWTs carry signed claims about a user, enabling stateless authentication without server-side session storage.
Question 2: How do you verify a JWT in an Express middleware using the jsonwebtoken package?
- jwt.verify(token, secret, callback) (Correct answer)
- jwt.decode(token, secret)
- jwt.check(token, secret)
- jwt.authenticate(token, secret)
Correct answer: jwt.verify(token, secret, callback)
jwt.verify() validates the token's signature and expiration, returning the decoded payload if valid.
Question 3: What HTTP header is conventionally used to send a JWT in an API request?
- Authorization: Bearer <token> (Correct answer)
- X-Auth-Token: <token>
- Token: <token>
- Auth: JWT <token>
Correct answer: Authorization: Bearer <token>
The Bearer token scheme in the Authorization header is the standard way to transmit JWTs with API requests.
Question 4: What does the helmet package help protect against in Express?
- XSS, clickjacking, and other attacks by setting security HTTP headers (Correct answer)
- SQL injection
- CSRF only
- Brute-force login attempts
Correct answer: XSS, clickjacking, and other attacks by setting security HTTP headers
helmet sets headers like Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security to mitigate common web attacks.
Question 5: Which middleware is commonly used to prevent Cross-Site Request Forgery (CSRF) in Express apps with sessions?
- csurf (or modern alternatives like csrf-csrf) (Correct answer)
- helmet
- cors
- express-validator
Correct answer: csurf (or modern alternatives like csrf-csrf)
CSRF middleware generates and validates per-session tokens to ensure requests originate from your own forms.
Question 6: What is the purpose of bcrypt when handling passwords in an Express application?
- Hashing passwords with a salt to securely store them (Correct answer)
- Encrypting passwords for transmission
- Generating JWT secrets
- Validating password format
Correct answer: Hashing passwords with a salt to securely store them
bcrypt applies a cost factor and salt to create a one-way hash, making password storage secure against rainbow table attacks.
What is the primary purpose of JSON Web Tokens (JWT) in an Express application?