如何通过Fastify从JWT令牌中获取用户名?
Fixing JWT Decoding in Your Fastify /decode Endpoint
Hey there! Let's walk through fixing the issues with your /decode endpoint. First, let's recap what might be going wrong, then jump into the corrected code.
Common Issues in Your Current Code
- No error handling for missing/invalid Authorization headers: If the header isn't present or doesn't follow the
Bearer <token>format, callingsplit(' ')onundefinedwill throw an error. - Not awaiting the verify method:
fastify.jwt.verifyis asynchronous—you need to useawaitto get the decoded payload instead of a pending Promise. - Missing error catching for invalid tokens: Tokens can be expired, tampered with, or have invalid signatures—you need to catch these failures.
- Ensure your signup payload includes the username: If your original
/signupdoesn't include the username in the JWT payload, you won't be able to extract it later!
Corrected Signup Endpoint (to include username)
First, let's make sure your /signup endpoint actually puts the username into the JWT payload:
fastify.post('/signup', (req, reply) => { // Extract username from the request body (adjust based on your actual input) const { username } = req.body; // Include username in the payload, plus an expiration for security const token = fastify.jwt.sign({ username, exp: Math.floor(Date.now() / 1000) + 60 * 60 // Token expires in 1 hour }); reply.send({ token }); });
Fixed Decode Endpoint with Error Handling
Now here's the complete /decode endpoint that addresses all the issues:
fastify.get('/decode', async (request, reply) => { try { // Validate the Authorization header exists and is correctly formatted const authHeader = request.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return reply.status(401).send({ error: 'Authorization header required. Format: Bearer <token>' }); } // Extract the token from the header const token = authHeader.split(' ')[1]; // Verify and decode the token (await this async method!) const decoded = await fastify.jwt.verify(token); // Return the extracted username return reply.send({ username: decoded.username }); } catch (err) { // Handle token verification failures (expired, invalid signature, etc.) return reply.status(401).send({ error: 'Failed to decode token', details: err.message }); } });
Key Notes
- Always validate headers first: Never assume the
Authorizationheader is present or correctly formatted—this prevents unexpected crashes. - Await async methods: Fastify's JWT verify method returns a Promise, so
awaitis mandatory to get the decoded payload. - Catch errors: Wrapping the logic in a
try/catchlets you gracefully handle invalid tokens and return meaningful error messages to clients. - Include user data in the JWT payload: Make sure the data you need (like username) is included when you sign the token in
/signup—you can't extract data that wasn't there in the first place!
内容的提问来源于stack exchange,提问作者sensorario
相关产品推荐
相关产品推荐

