0
0
Node.jsframework~10 mins

Session-based vs token-based auth in Node.js - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a session in Express using the express-session middleware.

Node.js
app.use(session({ secret: '[1]', resave: false, saveUninitialized: true }));
Drag options to blanks, or click blank then click option'
A'authToken'
B'token123'
C'mySecretKey'
D'sessionToken'
Attempts:
3 left
💡 Hint
Common Mistakes
Using token-like strings instead of a secret key.
Leaving the secret empty or undefined.
2fill in blank
medium

Complete the code to send a JWT token after user login.

Node.js
const token = jwt.[1]({ id: user.id }, 'secretKey', { expiresIn: '1h' });
Drag options to blanks, or click blank then click option'
Averify
Bsign
Cdecode
Dencrypt
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'verify' instead of 'sign' to create a token.
Using 'decode' which only reads tokens.
3fill in blank
hard

Fix the error in the middleware that checks for a JWT token in the Authorization header.

Node.js
const token = req.headers.authorization?.split(' ')[[1]];
Drag options to blanks, or click blank then click option'
A1
B-1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 which is the word 'Bearer'.
Using index 2 which is out of range.
4fill in blank
hard

Fill both blanks to create a middleware that destroys the session and clears the cookie on logout.

Node.js
req.session.[1](() => { res.[2]('sessionCookie'); res.send('Logged out'); });
Drag options to blanks, or click blank then click option'
Adestroy
BclearCookie
Cend
DremoveCookie
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'end' instead of 'destroy' for sessions.
Using 'removeCookie' which is not a valid Express method.
5fill in blank
hard

Fill all three blanks to create a token-based auth middleware that verifies the JWT token and attaches user info to the request.

Node.js
const token = req.headers.authorization?.split(' ')[[1]];
try {
  const decoded = jwt.[2](token, '[3]');
  req.user = decoded;
  next();
} catch (err) {
  res.status(401).send('Unauthorized');
}
Drag options to blanks, or click blank then click option'
A0
B1
Cverify
DsecretKey
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 which is 'Bearer' instead of the token.
Using 'sign' instead of 'verify' to check the token.
Using wrong or missing secret key.