Bird
Raised Fist0
Astroframework~10 mins

JWT authentication flow in Astro - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - JWT authentication flow
User sends login request
↓
Server verifies credentials
↓
Generate JWT
↓
Send JWT to user
↓
User stores JWT
↓
User sends JWT with requests
↓
Server verifies JWT
This flow shows how a user logs in, receives a JWT token, and uses it to access protected resources, with the server verifying the token each time.
Execution Sample
Astro
POST /login
  -> verify credentials
  -> if valid, create JWT
  -> send JWT to client
Client stores JWT
Client sends JWT in Authorization header
Server verifies JWT on each request
This code snippet shows the main steps of JWT authentication from login to token verification.
Execution Table
StepActionInputOutputNext Step
1User sends login requestusername, passwordRequest receivedServer verifies credentials
2Server verifies credentialsusername, passwordCredentials validGenerate JWT
3Generate JWTUser infoJWT token createdSend JWT to user
4Send JWT to userJWT tokenJWT sent in responseUser stores JWT
5User stores JWTJWT tokenJWT saved locallyUser sends JWT with requests
6User sends JWT with requestsJWT token in headerRequest with JWT receivedServer verifies JWT
7Server verifies JWTJWT tokenJWT validAllow access
8Allow accessValid JWTProtected resource sentEND
9If credentials invalidusername, passwordError responseEND
10If JWT invalidJWT tokenError responseEND
💡 Execution stops when user is either granted access with valid JWT or denied due to invalid credentials or token.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
usernameundefinedprovidedprovidedprovidedprovidedprovidedprovidedprovided
passwordundefinedprovidedprovidedprovidedprovidedprovidedprovidedprovided
credentials_validfalsetruetruetruetruetruetruetrue
JWT_tokennonenonecreatedsentstoredsentverifiedused
access_grantedfalsefalsefalsefalsefalsefalsetruetrue
Key Moments - 3 Insights
Why does the server generate a JWT only after verifying credentials?
Because the JWT proves the user is authenticated; generating it before verification would allow unauthorized access. See execution_table step 2 and 3.
What happens if the JWT sent by the user is invalid or expired?
The server rejects the request and sends an error response, stopping access. See execution_table step 10.
Why does the user store the JWT after login?
So the user can send it with future requests to prove authentication without logging in again. See execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 3?
AJWT token created
BJWT sent in response
CCredentials valid
DRequest received
💡 Hint
Check the 'Output' column for step 3 in the execution_table.
At which step does the server verify the JWT token sent by the user?
AStep 2
BStep 7
CStep 4
DStep 9
💡 Hint
Look for the step where 'Server verifies JWT' in the 'Action' column.
If the credentials are invalid, what is the next step according to the execution table?
AGenerate JWT
BSend JWT to user
CReject login with error response
DAllow access
💡 Hint
Check the row where credentials are invalid in the execution_table.
Concept Snapshot
JWT Authentication Flow:
1. User sends login with credentials.
2. Server verifies credentials.
3. If valid, server creates JWT.
4. JWT sent to user and stored.
5. User sends JWT with requests.
6. Server verifies JWT to allow access.
Full Transcript
This visual execution shows the JWT authentication flow in Astro framework. The user sends login credentials to the server. The server checks if credentials are valid. If yes, it creates a JWT token and sends it back. The user stores this token and includes it in future requests. The server verifies the token each time to allow or deny access. If credentials or token are invalid, the server rejects the request. This flow ensures secure access without sending passwords repeatedly.

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

  1. Step 1: Understand JWT role in authentication

    JWTs carry encoded user identity and permissions safely between client and server.
  2. 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.
  3. Final Answer:

    To securely transmit user identity and permissions between client and server -> Option A
  4. 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

  1. Step 1: Recall standard JWT header format

    The standard way to send JWT is in the Authorization header with 'Bearer' prefix.
  2. Step 2: Match options to standard

    Only Authorization: Bearer <token> matches the correct syntax: 'Authorization: Bearer <token>'. Others use incorrect header names or formats.
  3. Final Answer:

    Authorization: Bearer <token> -> Option A
  4. 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

  1. Step 1: Analyze token verification flow

    If token is invalid, jwt.verify throws an error caught by catch block.
  2. Step 2: Check catch block response

    The catch block returns status 403 with message 'Invalid token'.
  3. Final Answer:

    Response with status 403 and message 'Invalid token' -> Option C
  4. 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

  1. Step 1: Check how token is extracted

    Token is extracted using authHeader.split(' ')[0], which gets 'Bearer' instead of the token.
  2. Step 2: Identify correct token index

    The token is at index 1 after splitting by space, so index 0 is wrong.
  3. Final Answer:

    Token extraction uses wrong index from split -> Option B
  4. 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

  1. 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.
  2. 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.
  3. 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
  4. Quick Check:

    Secure refresh flow = memory + HttpOnly cookie [OK]
Hint: Keep refresh token HttpOnly, access token in memory [OK]
Common Mistakes:
  • Storing tokens in localStorage (XSS risk)
  • Never refreshing tokens (causes logout)
  • Putting tokens in URL (exposes tokens)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard