Installations
npm install @fastify/jwt
Score
99.2
Supply Chain
99.6
Quality
85.9
Maintenance
100
Vulnerability
100
License
Developer
fastify
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
20.8.0
NPM Version
10.1.0
Statistics
514 Stars
425 Commits
100 Forks
20 Watching
4 Branches
92 Contributors
Updated on 27 Nov 2024
Languages
JavaScript (94.58%)
TypeScript (5.42%)
Total Downloads
Cumulative downloads
Total Downloads
11,408,272
Last day
-2.9%
18,510
Compared to previous day
Last week
9.4%
113,340
Compared to previous week
Last month
-3.2%
474,239
Compared to previous month
Last year
268.6%
8,605,695
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
5
Dev Dependencies
7
@fastify/jwt
JWT utils for Fastify, internally it uses fast-jwt.
NOTE: The plugin has been migrated from using jsonwebtoken
to fast-jwt
. Even though fast-jwt
has 1:1 feature implementation with jsonwebtoken
, some exotic implementations might break. In that case please open an issue with details of your implementation. See Upgrading notes for more details about what changes this migration introduced.
@fastify/jwt
>= v9 supports Fastify@5.@fastify/jwt
< v9 supports Fastify@4.@fastify/jwt
< v6 supports Fastify@3.@fastify/jwt
v1.x supports both Fastify@2.
Install
npm i @fastify/jwt
Usage
Register as a plugin. This will decorate your fastify
instance with the following 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.
1const fastify = require('fastify')() 2fastify.register(require('@fastify/jwt'), { 3 secret: 'supersecret' 4}) 5 6fastify.post('/signup', (req, reply) => { 7 // some code 8 const token = fastify.jwt.sign({ payload }) 9 reply.send({ token }) 10}) 11 12fastify.listen({ port: 3000 }, err => { 13 if (err) throw err 14})
For verifying & accessing the decoded token inside your services, you can use a global onRequest
hook to define the verification process like so:
1const fastify = require('fastify')() 2fastify.register(require('@fastify/jwt'), { 3 secret: 'supersecret' 4}) 5 6fastify.addHook("onRequest", async (request, reply) => { 7 try { 8 await request.jwtVerify() 9 } catch (err) { 10 reply.send(err) 11 } 12})
Afterwards, just use request.user
in order to retrieve the user information:
1module.exports = async function(fastify, opts) { 2 fastify.get("/", async function(request, reply) { 3 return request.user 4 }) 5}
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
1const fp = require("fastify-plugin") 2 3module.exports = fp(async function(fastify, opts) { 4 fastify.register(require("@fastify/jwt"), { 5 secret: "supersecret" 6 }) 7 8 fastify.decorate("authenticate", async function(request, reply) { 9 try { 10 await request.jwtVerify() 11 } catch (err) { 12 reply.send(err) 13 } 14 }) 15})
Then use the onRequest
of a route to protect it & access the user information inside:
1module.exports = async function(fastify, opts) { 2 fastify.get( 3 "/", 4 { 5 onRequest: [fastify.authenticate] 6 }, 7 async function(request, reply) { 8 return request.user 9 } 10 ) 11}
Make sure that you also check @fastify/auth plugin for composing more complex strategies.
Auth0 tokens verification
If you need to verify Auth0 issued HS256 or RS256 JWT tokens, you can use fastify-auth0-verify, which is based on top of this module.
Options
secret
(required)
You must pass a secret
to the options
parameter. The secret
can be a primitive type String, a function that returns a String or an object { private, public }
.
In this object { private, public }
the private
key is a string, buffer or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { private: { key, passphrase }, public }
can be used (based on crypto documentation), in this case be sure you pass the algorithm
inside the signing options prefixed by the sign
key of the plugin registering options).
In this object { private, public }
the public
key is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.
Function based secret
is supported by the request.jwtVerify()
and reply.jwtSign()
methods and is called with request
, token
, and callback
parameters.
Verify-only mode
In cases where your incoming JWT tokens are issued by a trusted external
service, and you need only to verify their signature without issuing, there is
an option to configure fastify-jwt
in verify-only mode by passing the
secret
object containing only a public key: { public }
.
When only a public key is provided, decode and verification functions will work as
described below, but an exception will be thrown at an attempt to use any form
of sign
functionality.
Example
1const { readFileSync } = require('node:fs') 2const path = require('node:path') 3const fastify = require('fastify')() 4const jwt = require('@fastify/jwt') 5// secret as a string 6fastify.register(jwt, { secret: 'supersecret' }) 7// secret as a function with callback 8fastify.register(jwt, { 9 secret: function (request, token, callback) { 10 // do something 11 callback(null, 'supersecret') 12 } 13}) 14// secret as a function returning a promise 15fastify.register(jwt, { 16 secret: function (request, token) { 17 return Promise.resolve('supersecret') 18 } 19}) 20// secret as an async function 21fastify.register(jwt, { 22 secret: async function (request, token) { 23 return 'supersecret' 24 } 25}) 26// secret as an object of RSA keys (without passphrase) 27// the files are loaded as strings 28fastify.register(jwt, { 29 secret: { 30 private: readFileSync(`${path.join(__dirname, 'certs')}/private.key`, 'utf8'), 31 public: readFileSync(`${path.join(__dirname, 'certs')}/public.key`, 'utf8') 32 }, 33 sign: { algorithm: 'RS256' } 34}) 35// secret as an object of P-256 ECDSA keys (with a passphrase) 36// the files are loaded as buffers 37fastify.register(jwt, { 38 secret: { 39 private: { 40 key: readFileSync(`${path.join(__dirname, 'certs')}/private.pem`), 41 passphrase: 'super secret passphrase' 42 }, 43 public: readFileSync(`${path.join(__dirname, 'certs')}/public.pem`) 44 }, 45 sign: { algorithm: 'ES256' } 46}) 47// secret as an object with RSA public key 48// fastify-jwt is configured in VERIFY-ONLY mode 49fastify.register(jwt, { 50 secret: { 51 public: process.env.JWT_ISSUER_PUBKEY 52 } 53})
Default options
Optionally you can define global default options that will be used by @fastify/jwt
API if you do not override them.
Example
1const { readFileSync } = require('node:fs') 2const path = require('node:path') 3const fastify = require('fastify')() 4const jwt = require('@fastify/jwt') 5fastify.register(jwt, { 6 secret: { 7 private: readFileSync(`${path.join(__dirname, 'certs')}/private.pem`, 'utf8') 8 public: readFileSync(`${path.join(__dirname, 'certs')}/public.pem`, 'utf8') 9 }, 10 // Global default decoding method options 11 decode: { complete: true }, 12 // Global default signing method options 13 sign: { 14 algorithm: 'ES256', 15 iss: 'api.example.tld' 16 }, 17 // Global default verifying method options 18 verify: { allowedIss: 'api.example.tld' } 19}) 20 21fastify.get('/decode', async (request, reply) => { 22 // We clone the global signing options before modifying them 23 let altSignOptions = Object.assign({}, fastify.jwt.options.sign) 24 altSignOptions.iss = 'another.example.tld' 25 26 // We generate a token using the default sign options 27 const token = await reply.jwtSign({ foo: 'bar' }) 28 // We generate a token using overrided options 29 const tokenAlt = await reply.jwtSign({ foo: 'bar' }, altSignOptions) 30 31 // We decode the token using the default options 32 const decodedToken = fastify.jwt.decode(token) 33 34 // We decode the token using completely overided the default options 35 const decodedTokenAlt = fastify.jwt.decode(tokenAlt, { complete: false }) 36 37 return { decodedToken, decodedTokenAlt } 38 /** 39 * Will return: 40 * 41 * { 42 * "decodedToken": { 43 * "header": { 44 * "alg": "ES256", 45 * "typ": "JWT" 46 * }, 47 * "payload": { 48 * "foo": "bar", 49 * "iat": 1540305336 50 * "iss": "api.example.tld" 51 * }, 52 * "signature": "gVf5bzROYB4nPgQC0nbJTWCiJ3Ya51cyuP-N50cidYo" 53 * }, 54 * decodedTokenAlt: { 55 * "foo": "bar", 56 * "iat": 1540305337 57 * "iss": "another.example.tld" 58 * }, 59 * } 60 */ 61}) 62 63fastify.listen({ port: 3000 }, err => { 64 if (err) throw err 65})
cookie
Example using cookie
In some situations you may want to store a token in a cookie. This allows you to drastically reduce the attack surface of XSS on your web app with the httpOnly
and secure
flags. Cookies can be susceptible to CSRF. You can mitigate this by either setting the sameSite
flag to strict
, or by using a CSRF library such as @fastify/csrf
.
Note: This plugin will look for a decorated request with the cookies
property. @fastify/cookie
supports this feature, and therefore you should use it when using the cookie feature. The plugin will fallback to looking for the token in the authorization header if either of the following happens (even if the cookie option is enabled):
- The request has both the authorization and cookie header
- Cookie is empty, authorization header is present
If you are signing your cookie, you can set the signed
boolean to true
which will make sure the JWT is verified using the unsigned value.
1const fastify = require('fastify')() 2const jwt = require('@fastify/jwt') 3 4fastify.register(jwt, { 5 secret: 'foobar', 6 cookie: { 7 cookieName: 'token', 8 signed: false 9 } 10}) 11 12fastify 13 .register(require('@fastify/cookie')) 14 15fastify.get('/cookies', async (request, reply) => { 16 const token = await reply.jwtSign({ 17 name: 'foo', 18 role: ['admin', 'spy'] 19 }) 20 21 reply 22 .setCookie('token', token, { 23 domain: 'your.domain', 24 path: '/', 25 secure: true, // send cookie over HTTPS only 26 httpOnly: true, 27 sameSite: true // alternative CSRF protection 28 }) 29 .code(200) 30 .send('Cookie sent') 31}) 32 33fastify.addHook('onRequest', (request) => request.jwtVerify()) 34 35fastify.get('/verifycookie', (request, reply) => { 36 reply.send({ code: 'OK', message: 'it works!' }) 37}) 38 39fastify.listen({ port: 3000 }, err => { 40 if (err) throw err 41})
onlyCookie
Setting this options to true
will decode only the cookie in the request. This is useful for refreshToken implementations where the request typically has two tokens: token and refreshToken. The main authentication token usually has a shorter timeout and the refresh token normally stored in the cookie has a longer timeout. This allows you to check to make sure that the cookie token is still valid, as it could have a different expiring time than the main token. The payloads of the two different tokens could also be different.
1const fastify = require('fastify')() 2const jwt = require('@fastify/jwt') 3 4fastify.register(jwt, { 5 secret: 'foobar', 6 cookie: { 7 cookieName: 'refreshToken', 8 }, 9 sign: { 10 expiresIn: '10m' 11 } 12}) 13 14fastify 15 .register(require('@fastify/cookie')) 16 17fastify.get('/cookies', async (request, reply) => { 18 19 const token = await reply.jwtSign({ 20 name: 'foo' 21 }) 22 23 const refreshToken = await reply.jwtSign({ 24 name: 'bar' 25 }, {expiresIn: '1d'}) 26 27 reply 28 .setCookie('refreshToken', refreshToken, { 29 domain: 'your.domain', 30 path: '/', 31 secure: true, // send cookie over HTTPS only 32 httpOnly: true, 33 sameSite: true // alternative CSRF protection 34 }) 35 .code(200) 36 .send({token}) 37}) 38 39fastify.addHook('onRequest', (request) => request.jwtVerify({onlyCookie: true})) 40 41fastify.get('/verifycookie', (request, reply) => { 42 reply.send({ code: 'OK', message: 'it works!' }) 43}) 44 45fastify.listen({ port: 3000 }, err => { 46 if (err) throw err 47})
trusted
Additionally, it is also possible to reject tokens selectively (i.e. blacklisting) by providing the option trusted
with the following signature: (request, decodedToken) => boolean|Promise<boolean>|SignPayloadType|Promise<SignPayloadType>
where request
is a FastifyRequest
and decodedToken
is the parsed (and verified) token information. Its result should be false
or Promise<false>
if the token should be rejected or, otherwise, be true
or Promise<true>
if the token should be accepted and, considering that request.user
will be used after that, the return should be decodedToken
itself.
Example trusted tokens
1const fastify = require('fastify')() 2 3fastify.register(require('@fastify/jwt'), { 4 secret: 'foobar', 5 trusted: validateToken 6}) 7 8fastify.addHook('onRequest', (request) => request.jwtVerify()) 9 10fastify.get('/', (request, reply) => { 11 reply.send({ code: 'OK', message: 'it works!' }) 12}) 13 14fastify.listen({ port: 3000 }, (err) => { 15 if (err) { 16 throw err 17 } 18}) 19 20// ideally this function would do a query against some sort of storage to determine its outcome 21async function validateToken(request, decodedToken) { 22 const denylist = ['token1', 'token2'] 23 24 return !denylist.includes(decodedToken.jti) 25}
formatUser
Example with formatted user
You may customize the request.user
object setting a custom sync function as parameter:
1const fastify = require('fastify')(); 2fastify.register(require('@fastify/jwt'), { 3 formatUser: function (user) { 4 return { 5 departmentName: user.department_name, 6 name: user.name 7 } 8 }, 9 secret: 'supersecret' 10}); 11 12fastify.addHook('onRequest', (request, reply) => request.jwtVerify()); 13 14fastify.get("/", async (request, reply) => { 15 return `Hello, ${request.user.name} from ${request.user.departmentName}.`; 16});
namespace
To define multiple JWT validators on the same routes, you may use the
namespace
option. You can combine this with custom names for jwtVerify
,
jwtDecode
, and jwtSign
.
When you omit the jwtVerify
, jwtDecode
, or jwtSign
options, the default
function name will be <namespace>JwtVerify
, <namespace>JwtDecode
and
<namespace>JwtSign
correspondingly.
Example with namespace
1const fastify = require('fastify') 2 3fastify.register(jwt, { 4 secret: 'test', 5 namespace: 'security', 6 // will decorate request with `securityVerify`, `securitySign`, 7 // and default `securityJwtDecode` since no custom alias provided 8 jwtVerify: 'securityVerify', 9 jwtSign: 'securitySign' 10}) 11 12fastify.register(jwt, { 13 secret: 'fastify', 14 // will decorate request with default `airDropJwtVerify`, `airDropJwtSign`, 15 // and `airDropJwtDecode` since no custom aliases provided 16 namespace: 'airDrop' 17}) 18 19// use them like this: 20fastify.post('/sign/:namespace', async function (request, reply) { 21 switch (request.params.namespace) { 22 case 'security': 23 return reply.securitySign(request.body) 24 default: 25 return reply.airDropJwtSign(request.body) 26 } 27})
extractToken
Setting this option will allow you to extract a token using function passed in for extractToken
option. The function definition should be (request: FastifyRequest) => token
. Fastify JWT will check if this option is set, if this option is set it will use the function defined in the option. When this option is not set then it will follow the normal flow.
1const fastify = require('fastify') 2const jwt = require('@fastify/jwt') 3 4fastify.register(jwt, { secret: 'test', verify: { extractToken: (request) => request.headers.customauthheader } }) 5 6fastify.post('/sign', function (request, reply) { 7 return reply.jwtSign(request.body) 8 .then(function (token) { 9 return { token } 10 }) 11}) 12 13fastify.get('/verify', function (request, reply) { 14 // token avaiable via `request.headers.customauthheader` as defined in fastify.register above 15 return request.jwtVerify() 16 .then(function (decodedToken) { 17 return reply.send(decodedToken) 18 }) 19}) 20 21fastify.listen(3000, function (err) { 22 if (err) throw err 23})
Typescript
To simplify the use of namespaces in TypeScript you can use the FastifyJwtNamespace
helper type:
1declare module 'fastify' { 2 interface FastifyInstance extends 3 FastifyJwtNamespace<{namespace: 'security'}> { 4 } 5}
Alternatively you can type each key explicitly:
1declare module 'fastify' { 2 interface FastifyInstance extends 3 FastifyJwtNamespace<{ 4 jwtDecode: 'securityJwtDecode', 5 jwtSign: 'securityJwtSign', 6 jwtVerify: 'securityJwtVerify', 7 }> { } 8}
messages
For your convenience, you can override the default HTTP response messages sent when an unauthorized or bad request error occurs. You can choose the specific messages to override and the rest will fallback to the default messages. The object must be in the format specified in the example below.
Example
1const fastify = require('fastify') 2 3const myCustomMessages = { 4 badRequestErrorMessage: 'Format is Authorization: Bearer [token]', 5 badCookieRequestErrorMessage: 'Cookie could not be parsed in request', 6 noAuthorizationInHeaderMessage: 'No Authorization was found in request.headers', 7 noAuthorizationInCookieMessage: 'No Authorization was found in request.cookies', 8 authorizationTokenExpiredMessage: 'Authorization token expired', 9 authorizationTokenUntrusted: 'Untrusted authorization token', 10 authorizationTokenUnsigned: 'Unsigned authorization token' 11 // for the below message you can pass a sync function that must return a string as shown or a string 12 authorizationTokenInvalid: (err) => { 13 return `Authorization token is invalid: ${err.message}` 14 } 15} 16 17fastify.register(require('@fastify/jwt'), { 18 secret: 'supersecret', 19 messages: myCustomMessages 20})
Error Code
ERR_ASSERTION
- Missing required parameter or option
- Error Status Code:
500
- Error Message:
Missing ${required}
FST_JWT_BAD_REQUEST
- Bad format in request authorization header. Example of correct format Authorization: Bearer [token]
- Error Status Code:
400
- Error Message:
Format is Authorization: Bearer [token]
FST_JWT_BAD_COOKIE_REQUEST
- Cookie could not be parsed in request object
- Error Status Code:
400
- Error Message:
Cookie could not be parsed in request
FST_JWT_NO_AUTHORIZATION_IN_HEADER
- No Authorization header was found in request.headers
- Error Status Code:
401
- Error Message: `No Authorization was found in request.headers
FST_JWT_NO_AUTHORIZATION_IN_COOKIE
- No Authorization header was found in request.cookies
- Error Status Code:
401
- Error Message:
No Authorization was found in request.cookies
FST_JWT_AUTHORIZATION_TOKEN_EXPIRED
- Authorization token has expired
- Error Status Code:
401
- Error Message:
Authorization token expired
FST_JWT_AUTHORIZATION_TOKEN_INVALID
- Authorization token provided is invalid.
- Error Status Code:
401
- Error Message:
Authorization token is invalid: ${err.message}
FST_JWT_AUTHORIZATION_TOKEN_UNTRUSTED
- Untrusted authorization token was provided
- Error Status Code:
401
- Error Message:
Untrusted authorization token
FAST_JWT_MISSING_SIGNATURE
- Unsigned or missing authorization token
- Error Status Code:
401
- Error Message:
Unsigned authorization token
decoratorName
If this plugin is used together with fastify/passport, we might get an error as both plugins use the same name for a decorator. We can change the name of the decorator, or user
will default
Example
1const fastify = require('fastify') 2fastify.register(require('@fastify/jwt'), { 3 secret: 'supersecret', 4 decoratorName: 'customName' 5})
decode
complete
: Return an object with the decoded header, payload, signature and input (the token part before the signature), instead of just the content of the payload. Default isfalse
.checkTyp
: When validating the decoded header, setting this option forces the check of the typ property against this value. Example:checkTyp: 'JWT'
. Default isundefined
.
sign
-
key
: A string or a buffer containing the secret forHS*
algorithms or the PEM encoded public key forRS*
,PS*
,ES*
andEdDSA
algorithms. The key can also be a function accepting a Node style callback or a function returning a promise. If provided, it will override the value of secret provided in the options. -
algorithm
: The algorithm to use to sign the token. The default is autodetected from the key, using RS256 for RSA private keys, HS256 for plain secrets and the correspondent ES or EdDSA algorithms for EC or Ed* private keys. -
mutatePayload
: If set totrue
, the original payload will be modified in place (viaObject.assign
) by the signing function. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token. -
expiresIn
: Time span after which the token expires, added as theexp
claim in the payload. It is expressed in seconds or a string describing a time span (E.g.:60
,"2 days"
,"10h"
,"7d"
). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default ("120"
is equal to"120ms"
). This will override any existing value in the claim. -
notBefore
: Time span before the token is active, added as thenbf
claim in the payload. It is expressed in seconds or a string describing a time span (E.g.:60
,"2 days"
,"10h"
,"7d"
). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default ("120"
is equal to"120ms"
). This will override any existing value in the claim. -
... the rest of the sign options can be found here.
verify
key
: A string or a buffer containing the secret forHS*
algorithms or the PEM encoded public key forRS*
,PS*
,ES*
andEdDSA
algorithms. The key can also be a function accepting a Node style callback or a function returning a promise. If provided, it will override the value of secret provided in the options.algorithms
: List of strings with the names of the allowed algorithms. By default, all algorithms are accepted.complete
: Return an object with the decoded header, payload, signature and input (the token part before the signature), instead of just the content of the payload. Default isfalse
.cache
: A positive number specifying the size of the verified tokens cache (using LRU strategy). Setting this totrue
is equivalent to provide the size 1000. When enabled the performance is dramatically improved. By default the cache is disabled.cacheTTL
: The maximum time to live of a cache entry (in milliseconds). If the token has a earlier expiration or the verifier has a shortermaxAge
, the earlier takes precedence. The default is600000
, which is 10 minutes.maxAge
: The maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span (E.g.:60
,"2 days"
,"10h"
,"7d"
). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default ("120"
is equal to"120ms"
). By default this is not checked.- ... the rest of the verify options can be found here.
API Spec
fastify.jwt.sign(payload [,options] [,callback])
This method is used to sign the provided payload
. It returns the token.
The payload
must be an Object
. Can be used asynchronously by passing a callback function; synchronously without a callback.
options
must be an Object
and can contain sign options.
fastify.jwt.verify(token, [,options] [,callback])
This method is used to verify provided token. It accepts a token
(as Buffer
or a string
) and returns the payload or the sections of the token. Can be used asynchronously by passing a callback function; synchronously without a callback.
options
must be an Object
and can contain verify options.
Example
1const token = fastify.jwt.sign({ foo: 'bar' }) 2// synchronously 3const decoded = fastify.jwt.verify(token) 4// asycnhronously 5fastify.jwt.verify(token, (err, decoded) => { 6 if (err) fastify.log.error(err) 7 fastify.log.info(`Token verified. Foo is ${decoded.foo}`) 8})
fastify.jwt.decode(token [,options])
This method is used to decode the provided token. It accepts a token (as a Buffer
or a string
) and returns the payload or the sections of the token.
options
must be an Object
and can contain decode options.
Can only be used synchronously.
Example
1const token = fastify.jwt.sign({ foo: 'bar' }) 2const decoded = fastify.jwt.decode(token) 3fastify.log.info(`Decoded JWT: ${decoded}`)
fastify.jwt.options
For your convenience, the decode
, sign
, verify
and messages
options you specify during .register
are made available via fastify.jwt.options
that will return an object { decode, sign, verify, messages }
containing your options.
Example
1const { readFileSync } = require('node:fs') 2const path = require('node:path') 3const fastify = require('fastify')() 4const jwt = require('@fastify/jwt') 5fastify.register(jwt, { 6 secret: { 7 private: readFileSync(`${path.join(__dirname, 'certs')}/private.key`), 8 public: readFileSync(`${path.join(__dirname, 'certs')}/public.key`) 9 }, 10 sign: { 11 algorithm: 'RS256', 12 aud: 'foo', 13 iss: 'example.tld' 14 }, 15 verify: { 16 allowedAud: 'foo', 17 allowedIss: 'example.tld', 18 } 19}) 20 21fastify.get('/', (request, reply) => { 22 const globalOptions = fastify.jwt.options 23 24 // We recommend that you clone the options like this when you need to mutate them 25 // modifiedVerifyOptions = { audience: 'foo', issuer: 'example.tld' } 26 let modifiedVerifyOptions = Object.assign({}, fastify.jwt.options.verify) 27 modifiedVerifyOptions.allowedAud = 'bar' 28 modifiedVerifyOptions.allowedSub = 'test' 29 30 return { globalOptions, modifiedVerifyOptions } 31 /** 32 * Will return : 33 * { 34 * globalOptions: { 35 * decode: {}, 36 * sign: { 37 * algorithm: 'RS256', 38 * aud: 'foo', 39 * iss: 'example.tld' 40 * }, 41 * verify: { 42 * allowedAud: 'foo', 43 * allowedIss: 'example.tld' 44 * } 45 * }, 46 * modifiedVerifyOptions: { 47 * allowedAud: 'bar', 48 * allowedIss: 'example.tld', 49 * allowedSub: 'test' 50 * } 51 * } 52 */ 53}) 54 55fastify.listen({ port: 3000 }, err => { 56 if (err) throw err 57})
fastify.jwt.cookie
For your convenience, request.jwtVerify()
will look for the token in the cookies property of the decorated request. You must specify cookieName
. Refer to the cookie example to see sample usage and important caveats.
reply.jwtSign(payload, [options,] callback)
options
must be an Object
and can contain sign
options.
request.jwtVerify([options,] callback)
options
must be an Object
and can contain verify
and decode
options.
request.jwtDecode([options,] callback)
Decode a JWT without verifying.
options
must be an Object
and can contain verify
and decode
options.
Algorithms supported
The following algorithms are currently supported by fast-jwt that is internally used by @fastify/jwt
.
Name | Description |
---|---|
none | Empty algorithm - The token signature section will be empty |
HS256 | HMAC using SHA-256 hash algorithm |
HS384 | HMAC using SHA-384 hash algorithm |
HS512 | HMAC using SHA-512 hash algorithm |
ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm |
ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm |
ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm |
RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm |
RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm |
RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm |
PS256 | RSASSA-PSS using SHA-256 hash algorithm |
PS384 | RSASSA-PSS using SHA-384 hash algorithm |
PS512 | RSASSA-PSS using SHA-512 hash algorithm |
EdDSA | EdDSA tokens using Ed25519 or Ed448 keys, only supported on Node.js 12+ |
You can find the list here.
Examples
Certificates Generation
Here some example on how to generate certificates and use them, with or without passphrase.
Signing and verifying (jwtSign, jwtVerify)
1const fastify = require('fastify')() 2const jwt = require('@fastify/jwt') 3const request = require('request') 4 5fastify.register(jwt, { 6 secret: function (request, reply, callback) { 7 // do something 8 callback(null, 'supersecret') 9 } 10}) 11 12fastify.post('/sign', function (request, reply) { 13 reply.jwtSign(request.body.payload, function (err, token) { 14 return reply.send(err || { 'token': token }) 15 }) 16}) 17 18fastify.get('/verify', function (request, reply) { 19 request.jwtVerify(function (err, decoded) { 20 return reply.send(err || decoded) 21 }) 22}) 23 24fastify.listen({ port: 3000 }, function (err) { 25 if (err) fastify.log.error(err) 26 fastify.log.info(`Server live on port: ${fastify.server.address().port}`) 27 28 // sign payload and get JWT 29 request({ 30 method: 'POST', 31 headers: { 32 'Content-Type': 'application/json' 33 }, 34 body: { 35 payload: { 36 foo: 'bar' 37 } 38 }, 39 uri: `http://localhost:${fastify.server.address().port}/sign`, 40 json: true 41 }, function (err, response, body) { 42 if (err) fastify.log.error(err) 43 fastify.log.info(`JWT token is ${body.token}`) 44 45 // verify JWT 46 request({ 47 method: 'GET', 48 headers: { 49 'Content-Type': 'application/json', 50 authorization: 'Bearer ' + body.token 51 }, 52 uri: 'http://localhost:' + fastify.server.address().port + '/verify', 53 json: true 54 }, function (err, response, body) { 55 if (err) fastify.log.error(err) 56 fastify.log.info(`JWT verified. Foo is ${body.foo}`) 57 }) 58 }) 59})
Verifying with JWKS
The following example integrates the get-jwks package to fetch a JWKS and verify a JWT against a valid public JWK.
Example
1const Fastify = require('fastify') 2const fjwt = require('@fastify/jwt') 3const buildGetJwks = require('get-jwks') 4 5const fastify = Fastify() 6const getJwks = buildGetJwks() 7 8fastify.register(fjwt, { 9 decode: { complete: true }, 10 secret: (request, token) => { 11 const { header: { kid, alg }, payload: { iss } } = token 12 return getJwks.getPublicKey({ kid, domain: iss, alg }) 13 } 14}) 15 16fastify.addHook('onRequest', async (request, reply) => { 17 try { 18 await request.jwtVerify() 19 } catch (err) { 20 reply.send(err) 21 } 22}) 23 24fastify.listen({ port: 3000 })
TypeScript
This plugin has two available exports, the default plugin function fastifyJwt
and the plugin options object FastifyJWTOptions
.
Import them like so:
1import fastifyJwt, { FastifyJWTOptions } from '@fastify/jwt'
Define custom Payload Type and Attached User Type to request object
1// fastify-jwt.d.ts 2import "@fastify/jwt" 3 4declare module "@fastify/jwt" { 5 interface FastifyJWT { 6 payload: { id: number } // payload type is used for signing and verifying 7 user: { 8 id: number, 9 name: string, 10 age: number 11 } // user type is return type of `request.user` object 12 } 13} 14 15// index.ts 16fastify.get('/', async (request, reply) => { 17 request.user.name // string 18 19 const token = await reply.jwtSign({ 20 id: '123' 21 // ^ Type 'string' is not assignable to type 'number'. 22 }); 23}) 24
Acknowledgements
This project is kindly sponsored by:
License
Licensed under MIT.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
10 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/fastify/.github/SECURITY.md:1
- Info: Found linked content: github.com/fastify/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/fastify/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/fastify/.github/SECURITY.md:1
Reason
SAST tool is not run on all commits -- score normalized to 8
Details
- Warn: 17 commits out of 21 are checked with a SAST tool
Reason
Found 10/21 approved changesets -- score normalized to 4
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
7
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More