使用fastify检索JWT令牌的用户名

问题描述 投票:0回答:1

我能够创建一个JWT令牌:

fastify.post('/signup', (req, reply) => {
  const token = fastify.jwt.sign({
    payload,
  })
  reply.send({ token })
})

可以返回类似:

{ “令牌”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MjM3MDgyMzF9.HZqqiL7wwPaEQihUGoF7Y42Ia67HgKJ-1Ms38Nvcsmw”}

但如果我尝试从令牌的用户名进行解码

fastify.get('/decode', async (request, reply) => {
  const auth = request.headers.authorization;
  const token = auth.split(' ')[1]
  fastify.jwt.verify(token, (err, decoded) => {
    if (err) fastify.log.error(err)
    fastify.log.info('username : ' + decoded.username)
    reply.send({
      foo: decoded,
    })
  })
})

响应是:

{ “富”:{ “男孩” 1523660987}}

fastify
1个回答
0
投票

这是你需要的工作示例。您所订阅的内容注意:

const fastify = require('fastify')({ logger: true })
const fastifyJwt = require('fastify-jwt')

async function customJwtAuth(fastify, opts) {
  fastify.register(fastifyJwt, { secret: 'asecretthatsverylongandimportedfromanenvfile' })
  fastify.get('/signup', (req, reply) => {
    const token = fastify.jwt.sign({ username: 'John Doo', hello: 'world' })
    reply.send({ token })
  })


  fastify.get('/decode', async (request, reply) => {
    const auth = request.headers.authorization;
    const token = auth.split(' ')[1]

    fastify.jwt.verify(token, (err, decoded) => {
      if (err) fastify.log.error(err)
      fastify.log.info('username : ' + decoded.username)
      reply.send({ foo: decoded })
    })
  })
}

fastify.register(customJwtAuth)
fastify.listen(3000)

卷曲http://localhost:3000/signup

{ “令牌”: “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkpvaG4gRG9vIiwiaGVsbG8iOiJ3b3JsZCIsImlhdCI6MTU0OTg2ODk3MX0.T8kv8jbyp-3ianO8-CsfxZ5gePZG9PSjY8NvhdNV7uM”}

卷曲 'http://localhost:3000/decode' -H '授权:承载eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkpvaG4gRG9v IiwiaGVsbG8iOiJ3b3JsZCIsImlhdCI6MTU0OTg2ODk3MX0.T8kv8jbyp-3ianO8-CsfxZ5gePZG9PSjY8NvhdNV7uM'

{ “富”:{ “用户名”: “约翰·斗”, “你好”: “世界”, “IAT”:1549868971}}

© www.soinside.com 2019 - 2024. All rights reserved.