0
0
Expressframework~10 mins

JWT token verification middleware in Express - Interactive Code Practice

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

Complete the code to import the JWT library.

Express
const jwt = require('[1]');
Drag options to blanks, or click blank then click option'
Acors
Bjsonwebtoken
Cexpress
Dbody-parser
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'express' instead of 'jsonwebtoken' for JWT handling.
Trying to import a package that is unrelated to JWT.
2fill in blank
medium

Complete the code to extract the token from the Authorization header.

Express
const token = req.headers.authorization && req.headers.authorization.split(' ')[[1]];
Drag options to blanks, or click blank then click option'
A1
B0
C2
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 which gives 'Bearer' instead of the token.
Using index 2 which is out of range.
3fill in blank
hard

Fix the error in the token verification call.

Express
jwt.verify(token, process.env.JWT_SECRET, ([1], decoded) => {
  if (error) {
    return res.status(401).json({ message: 'Unauthorized' });
  }
  req.user = decoded;
  next();
});
Drag options to blanks, or click blank then click option'
Aerror
Be
Cerr
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the one checked inside the callback.
Not matching the error parameter with the variable used in the if condition.
4fill in blank
hard

Fill both blanks to create the middleware function and export it.

Express
function [1](req, res, next) {
  // middleware code here
}

module.exports = [2];
Drag options to blanks, or click blank then click option'
AverifyToken
BauthMiddleware
CverifyTokenMiddleware
DtokenVerifier
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the function and export.
Using generic names that don't describe the middleware purpose.
5fill in blank
hard

Fill all three blanks to complete the middleware that verifies the JWT token and handles errors.

Express
function verifyToken(req, res, next) {
  const token = req.headers.authorization && req.headers.authorization.split(' ')[[1]];
  if (!token) {
    return res.status(401).json({ message: '[2]' });
  }
  jwt.verify(token, process.env.JWT_SECRET, (error, decoded) => {
    if (error) {
      return res.status(401).json({ message: '[3]' });
    }
    req.user = decoded;
    next();
  });
}
Drag options to blanks, or click blank then click option'
A1
BNo token provided
CInvalid token
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong index for token extraction.
Using unclear or incorrect error messages.