Bird
Raised Fist0
GraphQLquery~20 mins

JWT integration in GraphQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JWT Integration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the primary purpose of JWT in database access?

Imagine you want to securely access your database through a web app. What role does JWT play in this process?

AIt encrypts the database data automatically without any extra configuration.
BIt stores the entire database schema inside the token for quick access.
CIt acts as a secure token to verify the user's identity and permissions before allowing database access.
DIt replaces the database with a JSON file for faster queries.
Attempts:
2 left
💡 Hint

Think about how a token helps confirm who you are before you get access.

❓ query_result
intermediate
2:00remaining
What is the output of this GraphQL query with JWT authorization?

Given a GraphQL query that requests user data, and a valid JWT token with user role 'admin', what will be the result?

GraphQL
query {
  users {
    id
    name
    email
  }
}

// JWT token payload: {"role": "admin"}
A[{"id": "1", "name": "Alice", "email": "alice@example.com"}, {"id": "2", "name": "Bob", "email": "bob@example.com"}]
BError: Unauthorized access - insufficient permissions
C[]
DError: Invalid JWT token
Attempts:
2 left
💡 Hint

Admins usually have full access to user data.

📝 Syntax
advanced
2:00remaining
Identify the syntax error in this JWT verification snippet in GraphQL resolver

Look at this code snippet that verifies a JWT token in a GraphQL resolver. Which option correctly fixes the syntax error?

GraphQL
const jwt = require('jsonwebtoken');

function verifyToken(token) {
  try {
    const decoded = jwt.verify(token, 'secretKey')
    return decoded;
  } catch (error) {
    throw new Error('Invalid token')
  }
}
ARemove the return statement to fix syntax.
BAdd a semicolon after jwt.verify(token, 'secretKey') to fix syntax: const decoded = jwt.verify(token, 'secretKey');
CReplace try-catch with if-else to fix syntax.
DChange 'secretKey' to secretKey without quotes to fix syntax.
Attempts:
2 left
💡 Hint

Check if all statements end properly.

❓ optimization
advanced
2:00remaining
How to optimize JWT usage to reduce database load in GraphQL API?

You want to reduce database queries by using JWT in your GraphQL API. Which approach is best?

AStore the entire user profile in the JWT token to eliminate database queries.
BUse JWT only for login and query the database for every request to ensure fresh data.
CEncrypt the JWT token with the database password to speed up queries.
DInclude user roles and permissions inside the JWT payload to avoid querying the database for each request.
Attempts:
2 left
💡 Hint

Think about what info in the token can help skip database checks.

🔧 Debug
expert
2:00remaining
Why does this GraphQL query fail with 'Invalid token' error despite a valid JWT?

Given this GraphQL resolver code snippet, why does the query fail with 'Invalid token' error even though the JWT token is valid?

GraphQL
const jwt = require('jsonwebtoken');

function resolver(parent, args, context) {
  const token = context.headers.authorization;
  try {
    const decoded = jwt.verify(token, process.env.SECRET);
    return getDataForUser(decoded.userId);
  } catch (e) {
    throw new Error('Invalid token');
  }
}

// Environment variable SECRET is not set.
AThe environment variable SECRET is missing, so jwt.verify fails to validate the token.
BThe token is expired, causing jwt.verify to throw an error.
CThe token is not passed in the authorization header.
DThe getDataForUser function is undefined, causing the error.
Attempts:
2 left
💡 Hint

Check if the secret used to verify the token is properly set.

Practice

(1/5)
1. What is the main purpose of using JWT in GraphQL database integration?
easy
A. To store large amounts of data
B. To speed up database queries
C. To verify the user's identity and secure database access
D. To format the GraphQL schema

Solution

  1. Step 1: Understand JWT role in security

    JWT (JSON Web Token) is used to confirm who the user is by verifying their identity.
  2. Step 2: Connect JWT to database access

    This verification controls who can access or change data in the GraphQL database.
  3. Final Answer:

    To verify the user's identity and secure database access -> Option C
  4. Quick Check:

    JWT secures access [OK]
Hint: JWT = user identity check for secure access [OK]
Common Mistakes:
  • Thinking JWT speeds up queries
  • Confusing JWT with data storage
  • Assuming JWT changes schema format
2. Which is the correct way to send a JWT token in a GraphQL request header?
easy
A. Token: Authorization <token>
B. Authorization: Token <token>
C. Auth: Bearer <token>
D. Authorization: Bearer <token>

Solution

  1. Step 1: Recall standard JWT header format

    The JWT token is sent in the HTTP header named 'Authorization' with the prefix 'Bearer'.
  2. Step 2: Match the correct header syntax

    The correct syntax is 'Authorization: Bearer <token>'. Other options use wrong header names or order.
  3. Final Answer:

    Authorization: Bearer <token> -> Option D
  4. Quick Check:

    JWT header uses Bearer prefix [OK]
Hint: JWT always uses 'Authorization: Bearer <token>' header [OK]
Common Mistakes:
  • Using 'Token' instead of 'Bearer'
  • Wrong header name like 'Auth'
  • Mixing order of 'Token' and 'Authorization'
3. Given this GraphQL resolver snippet using JWT:
const user = verifyToken(context.headers.authorization);
if (!user) return null;
return db.getUserData(user.id);
What happens if the token is invalid or missing?
medium
A. The resolver returns null and no data is fetched
B. The resolver throws a syntax error
C. The resolver returns all user data without restriction
D. The resolver crashes the server

Solution

  1. Step 1: Analyze token verification

    The function verifyToken returns null or false if the token is invalid or missing.
  2. Step 2: Check resolver behavior on invalid token

    If user is falsy, the resolver returns null, meaning no data is sent back.
  3. Final Answer:

    The resolver returns null and no data is fetched -> Option A
  4. Quick Check:

    Invalid token leads to null return [OK]
Hint: Invalid token means no user, so resolver returns null [OK]
Common Mistakes:
  • Expecting a syntax error on invalid token
  • Assuming data is returned without user
  • Thinking server crashes on bad token
4. Identify the error in this JWT integration snippet:
const token = context.headers.Authorization;
const user = verifyToken(token);
if (!user) throw new Error('Unauthorized');
return db.getUserData(user.id);
medium
A. verifyToken should be called with context.token, not token
B. Header name should be lowercase 'authorization', not 'Authorization'
C. The error message should be 'Forbidden' instead of 'Unauthorized'
D. db.getUserData should be called before verifying the token

Solution

  1. Step 1: Check header name case sensitivity

    HTTP headers in Node.js are usually lowercase, so 'authorization' is correct, not 'Authorization'.
  2. Step 2: Confirm token extraction correctness

    Using 'Authorization' may cause token to be undefined, leading to verification failure.
  3. Final Answer:

    Header name should be lowercase 'authorization', not 'Authorization' -> Option B
  4. Quick Check:

    Header keys are lowercase [OK]
Hint: Use lowercase 'authorization' header key in code [OK]
Common Mistakes:
  • Using uppercase header keys in Node.js
  • Calling db before verifying user
  • Confusing error message types
5. You want to restrict a GraphQL query so only users with role 'admin' can access sensitive data. Which JWT integration approach is best?
hard
A. Verify token, then check if user.role === 'admin' before returning data
B. Return data first, then verify token asynchronously
C. Skip token verification and rely on frontend checks
D. Verify token but ignore user roles for simplicity

Solution

  1. Step 1: Understand role-based access control

    To restrict access, verify the token and check the user's role before sending data.
  2. Step 2: Evaluate options for security

    Returning data before verification or skipping roles risks exposing sensitive info.
  3. Final Answer:

    Verify token, then check if user.role === 'admin' before returning data -> Option A
  4. Quick Check:

    Check role after token verification [OK]
Hint: Check user role after verifying JWT token [OK]
Common Mistakes:
  • Sending data before verifying user
  • Ignoring roles in backend checks
  • Trusting frontend for security
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