What does JWT stand for and what is its main purpose?
JWT stands for JSON Web Token. It is used to securely transmit information between a client and server as a JSON object, mainly for authentication and authorization.
Click to reveal answer
beginner
In the JWT authentication flow, what happens after the user submits their login credentials?
The server verifies the credentials. If valid, it creates a JWT containing user info and signs it. Then, it sends the JWT back to the client to use for future requests.
Click to reveal answer
beginner
How does the client use the JWT after receiving it from the server?
The client stores the JWT (usually in localStorage or cookies) and includes it in the Authorization header of future requests to access protected resources.
Click to reveal answer
intermediate
What role does the server play when it receives a request with a JWT?
The server checks the JWT's signature and validity. If the token is valid and not expired, the server allows access to the requested resource; otherwise, it denies access.
Click to reveal answer
intermediate
Why is it important to set an expiration time on a JWT?
Setting an expiration time limits how long a token is valid, reducing security risks if a token is stolen. It forces users to re-authenticate after some time.
Click to reveal answer
What does the server send back to the client after successful login in JWT flow?
APlain user data
BUser password
CA signed JWT token
DSession ID cookie
✗ Incorrect
The server sends a signed JWT token that the client uses for future authentication.
Where does the client usually store the JWT token?
AIn localStorage or cookies
BIn the server database
CIn the URL query string
DIn a hidden form field
✗ Incorrect
Clients typically store JWTs in localStorage or cookies to include them in future requests.
What header does the client use to send the JWT token to the server?
AAccept
BAuthorization
CContent-Type
DCookie
✗ Incorrect
The JWT is sent in the Authorization header, usually as 'Bearer '.
What does the server check to validate a JWT token?
ASignature and expiration
BUser password
CClient IP address
DToken size
✗ Incorrect
The server verifies the token's signature and checks if it has expired.
Why should JWT tokens have an expiration time?
ATo avoid using HTTPS
BTo make tokens larger
CTo store user passwords
DTo limit token validity and improve security
✗ Incorrect
Expiration limits token lifetime, reducing risk if stolen.
Describe the full JWT authentication flow from login to accessing a protected resource.
Think about what happens step-by-step between client and server.
You got /8 concepts.
Explain why JWT tokens are useful for stateless authentication in web apps.
Consider how JWT helps avoid server-side session storage.
You got /5 concepts.
Practice
(1/5)
1. What is the main purpose of a JWT (JSON Web Token) in authentication?
easy
A. To securely transmit user identity and permissions between client and server
B. To store user passwords on the client side
C. To encrypt all user data in the database
D. To replace cookies for storing session data only
Solution
Step 1: Understand JWT role in authentication
JWTs carry encoded user identity and permissions safely between client and server.
Step 2: Compare options with JWT purpose
Only To securely transmit user identity and permissions between client and server correctly describes JWT's role; others confuse JWT with password storage or encryption.
Final Answer:
To securely transmit user identity and permissions between client and server -> Option A
Quick Check:
JWT purpose = secure token for identity [OK]
Hint: JWTs carry user info safely between client and server [OK]
Common Mistakes:
Thinking JWT stores passwords
Confusing JWT with database encryption
Assuming JWT replaces cookies entirely
2. Which of the following is the correct way to send a JWT token in an HTTP request header?
easy
A. Authorization: Bearer <token>
B. Token: JWT <token>
C. Auth-Token: <token>
D. JWT-Authorization: Bearer <token>
Solution
Step 1: Recall standard JWT header format
The standard way to send JWT is in the Authorization header with 'Bearer' prefix.
Step 2: Match options to standard
Only Authorization: Bearer <token> matches the correct syntax: 'Authorization: Bearer <token>'. Others use incorrect header names or formats.
Final Answer:
Authorization: Bearer <token> -> Option A
Quick Check:
JWT header = Authorization: Bearer token [OK]
Hint: JWTs go in 'Authorization: Bearer <token>' header [OK]
Common Mistakes:
Using wrong header names like 'Token' or 'Auth-Token'
Omitting 'Bearer' prefix
Adding extra words like 'JWT' before token
3. Given this Astro server code snippet handling JWT verification, what will be the output if the token is invalid?
import jwt from 'jsonwebtoken';
export async function get({ request }) {
const authHeader = request.headers.get('Authorization');
if (!authHeader) return new Response('No token', { status: 401 });
const token = authHeader.split(' ')[1];
try {
const user = jwt.verify(token, 'secretkey');
return new Response(`User: ${user.name}`, { status: 200 });
} catch {
return new Response('Invalid token', { status: 403 });
}
}
medium
A. Response with status 200 and user name
B. Response with status 401 and message 'No token'
C. Response with status 403 and message 'Invalid token'
D. Response with status 500 and server error message
Solution
Step 1: Analyze token verification flow
If token is invalid, jwt.verify throws an error caught by catch block.
Step 2: Check catch block response
The catch block returns status 403 with message 'Invalid token'.
Final Answer:
Response with status 403 and message 'Invalid token' -> Option C
Quick Check:
Invalid token triggers 403 response [OK]
Hint: Invalid JWT triggers catch block with 403 response [OK]
Common Mistakes:
Assuming invalid token returns 401
Confusing catch block with success path
Expecting server error instead of 403
4. Identify the bug in this Astro JWT authentication snippet:
export async function get({ request }) {
const authHeader = request.headers.get('Authorization');
if (!authHeader) return new Response('No token', { status: 401 });
const token = authHeader.split(' ')[0];
try {
const user = jwt.verify(token, 'secretkey');
return new Response(`User: ${user.name}`, { status: 200 });
} catch {
return new Response('Invalid token', { status: 403 });
}
}
medium
A. Missing secret key in jwt.verify call
B. Token extraction uses wrong index from split
C. No check for missing Authorization header
D. Response status codes are reversed
Solution
Step 1: Check how token is extracted
Token is extracted using authHeader.split(' ')[0], which gets 'Bearer' instead of the token.
Step 2: Identify correct token index
The token is at index 1 after splitting by space, so index 0 is wrong.
Final Answer:
Token extraction uses wrong index from split -> Option B
Quick Check:
Token index must be 1, not 0 [OK]
Hint: Token is after 'Bearer', so use split index 1 [OK]
Common Mistakes:
Using split index 0 instead of 1
Forgetting to check Authorization header
Mixing up status codes 401 and 403
5. You want to implement a refresh token flow in Astro using JWT. Which approach correctly handles token expiration and refresh securely?
hard
A. Send access token only once at login and never refresh it; rely on long expiration time
B. Store both access and refresh tokens in localStorage and refresh access token automatically on every request
C. Store refresh token in localStorage and access token in URL query parameters for easy access
D. Store access token in memory and refresh token in HttpOnly cookie; use refresh token to get new access token when expired
Solution
Step 1: Understand secure token storage
Access tokens should be stored in memory to reduce exposure; refresh tokens in HttpOnly cookies to prevent JavaScript access.
Step 2: Use refresh token to get new access token
When access token expires, client uses refresh token securely to request a new access token.
Final Answer:
Store access token in memory and refresh token in HttpOnly cookie; use refresh token to get new access token when expired -> Option D