2

我能够创建一个 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,
    })
  })
})

回应是:

{"foo":{"iat":1523660987}}

4

1 回答 1

4

这是您需要的一个工作示例。注意你签署的内容:

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

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkpvaG4gRG9vIiwiaGVsbG8iOiJ3b3JsZCIsImlhdCI6MTU0OTg2ODk3MX0.T8kv8jbyp-3ianO8-CsfxZ5gePZvuGNHPSj"}

curl ' http://localhost:3000/decode ' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkpvaG4gRG9v IiwiaGVsbG8iOiJ3b3JsZCIsImlhdCI6MTU0OTg2ODk3MX0.T8kv8jbyp-3ianO8-CsfxZ5gePZG9PSjY8NvhdNV7uM'

{"foo":{"username":"John Doo","hello":"world","iat":1549868971}}

于 2019-02-11T07:13:22.480 回答