Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
fastify-jwt
Advanced tools
JWT utils for Fastify, internally uses jsonwebtoken.
npm i fastify-jwt --save
Register as a plugin. This will decorate your fastify
instance with the standard jsonwebtoken methods decode
, sign
, and verify
; refer to their documentation to find how to use the utilities. It will also register request.jwtVerify
and reply.jwtSign
. You must pass a secret
when registering the plugin.
const fastify = require('fastify')
fastify.register(require('fastify-jwt'), {
secret: 'supersecret'
})
fastify.post('/signup', (req, reply) => {
// some code
const token = fastify.jwt.sign({ payload })
reply.send({ token })
})
fastify.listen(3000, err => {
if (err) throw err
})
For verifying & accessing the decoded token inside your services, you can use a global preHandler
hook to define the verification process like so:
const fastify = require('fastify')
fastify.register(require('fastify-jwt'), {
secret: 'supersecret'
})
fastify.addHook("preHandler", async (request, reply) => {
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
})
Aftewards, just use request.user
in order to retrieve the user information:
module.exports = async function(fastify, opts) {
fastify.get("/", async function(request, reply) {
return request.user
})
}
However, most of the time we want to protect only some of the routes in our application. To achieve this you can wrap your authentication logic into a plugin like
const fp = require("fastify-plugin")
module.exports = fp(async function(fastify, opts) {
fastify.register(require("fastify-jwt"), {
secret: "supersecret"
})
fastify.decorate("authenticate", async function(request, reply) {
try {
await request.jwtVerify()
} catch (err) {
reply.send(err)
}
})
})
Then use the beforeHandler
of a route to protect it & access the user information inside:
module.exports = async function(fastify, opts) {
fastify.get(
"/",
{
beforeHandler: [fastify.authenticate]
},
async function(request, reply) {
return request.user
}
)
}
Make sure that you also check fastify-auth plugin for composing more complex strategies.
fastify-jwt
is a fastify plugin. You must pass a secret
to the options
parameter. The secret
can be a primitive type String or a function that returns a String. Function based secret
is supported by the request.jwtVerify()
and reply.jwtSign()
methods and is called with request
, reply
, and callback
parameters.
const fastify = require('fastify')()
const jwt = require('fastify-jwt')
// secret as a string
fastify.register(jwt, { secret: 'supersecret' })
// secret as a function
fastify.register(jwt, {
secret: function (request, reply, callback) {
// do something
callback(null, 'supersecret')
}
})
The sign
method is an implementation of jsonwebtoken .sign()
. Can be used asynchronously by passing a callback function; synchronously without a callback.
The verify
method is an implementation of jsonwebtoken .verify()
. Can be used asynchronously by passing a callback function; synchronously without a callback.
const token = fastify.jwt.sign({ foo: 'bar' })
// synchronously
const decoded = fastify.jwt.verify(token)
// asycnhronously
fastify.jwt.verify(token, (err, decoded) => {
if (err) fastify.log.error(err)
fastify.log.info(`Token verified. Foo is ${decoded.foo}`)
})
The decode
method is an implementation of jsonwebtoken .decode()
. Can only be used synchronously.
const token = fastify.jwt.sign({ foo: 'bar' })
const decoded = fastify.jwt.decode(token)
fastify.log.info(`Decoded JWT: ${decoded}`)
For your convenience, the secret
you specify during .register
is made available via fastify.jwt.secret
. request.jwtVerify()
and reply.jwtSign()
will wrap non-function secrets in a callback function. request.jwtVerify()
and reply.jwtSign()
use an asynchronous waterfall method to retrieve your secret. It's recommended that your use these methods if your secret
method is asynchronous.
These methods are very similar to their standard jsonwebtoken counterparts.
const fastify = require('fastify')()
fastify.register(jwt, {
secret: function (request, reply, callback) {
// do something
callback(null, 'supersecret')
}
})
fastify.post('/sign', function (request, reply) {
reply.jwtSign(request.body.payload, function (err, token) {
return reply.send(err || { 'token': token })
})
})
fastify.get('/verify', function (request, reply) {
request.jwtVerify(function (err, decoded) {
return reply.send(err || decoded)
})
})
fastify.listen(3000, function (err) {
if (err) fastify.log.error(err)
fastify.log.info(`Server live on port: ${fastify.server.address().port}`)
// sign payload and get JWT
request({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
payload: {
foo: 'bar'
}
},
uri: `http://localhost:${fastify.server.address().port}/sign`,
json: true
}, function (err, response, body) {
if (err) fastify.log.error(err)
fastify.log.info(`JWT token is ${body}`)
// verify JWT
request({
method: 'GET',
headers: {
'Content-Type': 'application/json',
authorization: 'Bearer ' + sign.token
},
uri: 'http://localhost:' + fastify.server.address().port + '/verify',
json: true
}, function (err, response, body) {
if (err) fastify.log.error(err)
fastify.log.info(`JWT verified. Foo is ${body.bar}`)
})
})
})
This project is kindly sponsored by:
Licensed under MIT.
FAQs
`fastify-jwt@4.2.0` has been deprecated. Please use `@fastify/jwt@5.0.0` instead.
The npm package fastify-jwt receives a total of 4,705 weekly downloads. As such, fastify-jwt popularity was classified as popular.
We found that fastify-jwt demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 17 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.