📖 Scenario: You are building a simple authentication system for a web app. You need to create and verify JWT tokens to securely identify users.
🎯 Goal: Build a Node.js script that generates a JWT token for a user and then verifies it to confirm the user's identity.
📋 What You'll Learn
Create a user object with exact properties
Define a secret key string for signing tokens
Generate a JWT token using the user object and secret key
Verify the JWT token using the secret key
💡 Why This Matters
🌍 Real World
JWT tokens are widely used in web apps to securely identify users without storing session data on the server.
💼 Career
Understanding JWT token generation and verification is essential for backend developers working on authentication and authorization.
Progress0 / 4 steps
1
Create the user data object
Create a constant called user with these exact properties: id set to 123, username set to 'alice', and role set to 'admin'.
Node.js
Hint
Use const user = { id: 123, username: 'alice', role: 'admin' }; to create the user object.
2
Define the secret key
Create a constant called secretKey and set it to the string 'mysecretkey'.
Node.js
Hint
Use const secretKey = 'mysecretkey'; to define the secret key.
3
Generate the JWT token
Import the jsonwebtoken package and create a constant called token by signing the user object with secretKey using jwt.sign().
Node.js
Hint
Use const jwt = require('jsonwebtoken'); to import and const token = jwt.sign(user, secretKey); to create the token.
4
Verify the JWT token
Create a constant called verifiedUser by verifying the token with secretKey using jwt.verify().
Node.js
Hint
Use const verifiedUser = jwt.verify(token, secretKey); to verify the token.
Practice
(1/5)
1. What is the main purpose of a JWT token in a Node.js application?
easy
A. To securely transmit user identity without sending passwords repeatedly
B. To store user passwords in the database
C. To encrypt all user data on the server
D. To create a permanent session without expiration
Solution
Step 1: Understand JWT token purpose
JWT tokens are used to prove user identity securely without sending passwords every time.
Step 2: Compare options
Only To securely transmit user identity without sending passwords repeatedly correctly describes this purpose; others describe unrelated or incorrect uses.
Final Answer:
To securely transmit user identity without sending passwords repeatedly -> Option A
Quick Check:
JWT purpose = Secure identity proof [OK]
Hint: JWT = identity proof without password resend [OK]
Common Mistakes:
Thinking JWT stores passwords
Confusing JWT with encryption of all data
Assuming JWT creates permanent sessions
2. Which of the following is the correct syntax to generate a JWT token using the jsonwebtoken library in Node.js?
easy
A. jwt.generate(payload, secretKey, { expiresAt: '1h' })
B. jwt.create(payload, secretKey, { expiresIn: '1h' })
C. jwt.sign(payload, secretKey, { expiresIn: '1h' })
D. jwt.make(payload, secretKey, { expire: '1h' })
Solution
Step 1: Recall jsonwebtoken method for token creation
The correct method to create a token is jwt.sign with payload, secret, and options.
Step 2: Check option syntax
Only jwt.sign(payload, secretKey, { expiresIn: '1h' }) uses jwt.sign and correct option key expiresIn; others use invalid method names or option keys.
Final Answer:
jwt.sign(payload, secretKey, { expiresIn: '1h' }) -> Option C
Quick Check:
Token creation method = jwt.sign [OK]
Hint: Use jwt.sign() with expiresIn option for token creation [OK]
Step 1: Check token creation and verification secrets
Token is signed with 'mysecret' but verified with 'wrongsecret', causing verification failure.
Step 2: Understand jwt.verify behavior on secret mismatch
jwt.verify throws an error if secret does not match, so decoded.id is not accessible.
Final Answer:
Secret key used for verification is incorrect -> Option D
Quick Check:
Secret mismatch = verification error [OK]
Hint: Verify with same secret as sign to avoid errors [OK]
Common Mistakes:
Assuming token expired without expiration set
Thinking payload lacks id property
Misusing jwt.sign method syntax
5. You want to generate a JWT token that expires in 30 minutes and includes the user's email and role. Which code snippet correctly does this using the jsonwebtoken library?
Step 1: Identify correct payload and expiration option
The payload includes email and role, and expiration uses expiresIn with '30m' for 30 minutes.
Step 2: Validate option keys and values
Only jwt.sign({ email: user.email, role: user.role }, 'secretKey', { expiresIn: '30m' }) uses correct option key expiresIn and valid time format '30m'; others use invalid keys or formats.