You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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, calling split(' ') on undefined will throw an error.
  • Not awaiting the verify method: fastify.jwt.verify is asynchronous—you need to use await to 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 /signup doesn'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 Authorization header is present or correctly formatted—this prevents unexpected crashes.
  • Await async methods: Fastify's JWT verify method returns a Promise, so await is mandatory to get the decoded payload.
  • Catch errors: Wrapping the logic in a try/catch lets 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:46:46