gpt4 book ai didi

fastify - 使用 fastify 从 jwt-token 检索用户名

转载 作者:行者123 更新时间:2023-12-02 20:26:21 25 4
gpt4 key购买 nike

我能够创建 jwt token :

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

可以返回如下内容:

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1MjM3MDgyMzF9.HZqqiL7wwPaEQihUGoF7Y42Ia67HgKJ-1Ms38Nvcsmw"}

但是如果我尝试从 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,
})
})
})

响应是:

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

最佳答案

这是一个满足您需求的工作示例。请注意您所签署的内容:

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)

curl http://localhost:3000/signup

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

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

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

关于fastify - 使用 fastify 从 jwt-token 检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com