Imagine you want to securely access your database through a web app. What role does JWT play in this process?
Think about how a token helps confirm who you are before you get access.
JWT (JSON Web Token) is used to securely transmit information about a user, including their identity and permissions. This helps the system decide if the user can access certain database resources.
Given a GraphQL query that requests user data, and a valid JWT token with user role 'admin', what will be the result?
query {
users {
id
name
email
}
}
// JWT token payload: {"role": "admin"}Admins usually have full access to user data.
The JWT token shows the user has the 'admin' role, which grants permission to fetch all users. So the query returns the full list of users.
Look at this code snippet that verifies a JWT token in a GraphQL resolver. Which option correctly fixes the syntax error?
const jwt = require('jsonwebtoken'); function verifyToken(token) { try { const decoded = jwt.verify(token, 'secretKey') return decoded; } catch (error) { throw new Error('Invalid token') } }
Check if all statements end properly.
JavaScript statements should end with semicolons to avoid syntax errors. Adding a semicolon after jwt.verify fixes the syntax.
You want to reduce database queries by using JWT in your GraphQL API. Which approach is best?
Think about what info in the token can help skip database checks.
Including roles and permissions in the JWT lets the API verify access without querying the database every time, improving performance.
Given this GraphQL resolver code snippet, why does the query fail with 'Invalid token' error even though the JWT token is valid?
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.
Check if the secret used to verify the token is properly set.
jwt.verify needs the secret key to validate the token. If the environment variable SECRET is missing, verification fails and throws an error.