使用fastify

时间:2018-04-14 12:22:28

标签: fastify

我可以创建一个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}}

1 个答案:

答案 0 :(得分: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.eyJ1c2VybmFtZSI6IkpvaG4gRG9vIiwiaGVsbG8iOiJ3b3JsZCIsImhdC6M8K8Z8K8K8K8K8Z8K8K7K8K8K8Z8K8K8K8K8K7K8Z8J8K7K8J8K8J8J7J4J8J7J7J7J7J7J4J6J8J7J茨0J8K8Z8J8J9JeJeJeJeJ9C4K8K9K9Z4K4Z5K4K8K9KXJ2KXZXJZJKJZXJKJXK      

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

     

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