fastify-jwt
JWT utils for Fastify, internally uses jsonwebtoken.
Install
npm i fastify-jwt --save
Usage
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 = fastify fastify fastify
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 = fastify fastify
Aftewards, just use request.user
in order to retrieve the user information:
module { fastify}
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 = moduleexports =
Then use the beforeHandler
of a route to protect it & access the user information inside:
module { fastify}
Make sure that you also check fastify-auth plugin for composing more complex strategies.
API Spec
fastify-jwt
fastify-jwt
is a fastify plugin. 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
, reply
, and callback
parameters.
Example
const readFileSync = const path = const fastify = const jwt = // secret as a stringfastify// secret as a functionfastify// secret as an object of RSA keys (without passphrase)// the files are loaded as stringsfastify// secret as an object of P-256 ECDSA keys (with a passphrase)// the files are loaded as buffersfastify
Optionaly you can define global default options that will be used by fastify-jwt
API if you don't override them.
Example
const readFileSync = const path = const fastify = const jwt = fastify fastify fastify
fastify.jwt.sign(payload [,options] [,callback])
The sign
method is an implementation of jsonwebtoken .sign()
. Can be used asynchronously by passing a callback function; synchronously without a callback.
fastify.jwt.verify(token, [,options] [,callback])
The verify
method is an implementation of jsonwebtoken .verify()
. Can be used asynchronously by passing a callback function; synchronously without a callback.
Example
const token = fastifyjwt// synchronouslyconst decoded = fastifyjwt// asycnhronouslyfastifyjwt
fastify.jwt.decode(token [,options])
The decode
method is an implementation of jsonwebtoken .decode()
. Can only be used synchronously.
Example
const token = fastifyjwtconst decoded = fastifyjwtfastifylog
fastify.jwt.options
For your convenience, the decode
, sign
and verify
options you specify during .register
are made available via fastify.jwt.options
that will return an object { decode, sign, verify }
containing your options.
Example
const readFileSync = const path = const fastify = const jwt = fastify fastify fastify
decode options
json
: force JSON.parse on the payload even if the header doesn't contain"typ":"JWT"
.complete
: return an object with the decoded payload and header.
sign options
algorithm
(default:HS256
)expiresIn
: expressed in seconds or a string describing a time span zeit/ms. Eg: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"
).notBefore
: expressed in seconds or a string describing a time span zeit/ms. Eg: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"
).audience
issuer
jwtid
subject
noTimestamp
header
keyid
mutatePayload
: if true, the sign function will modify the payload object directly. 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.
verify options
algorithms
: List of strings with the names of the allowed algorithms. For instance,["HS256", "HS384"]
.audience
: if you want to check audience (aud
), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions. Eg:"urn:foo"
,/urn:f[o]{2}/
,[/urn:f[o]{2}/, "urn:bar"]
issuer
(optional): string or array of strings of valid values for theiss
field.ignoreExpiration
: iftrue
do not validate the expiration of the token.ignoreNotBefore
...subject
: if you want to check subject (sub
), provide a value hereclockTolerance
: number of seconds to tolerate when checking thenbf
andexp
claims, to deal with small clock differences among different serversmaxAge
: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span zeit/ms. Eg:1000
,"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"
).clockTimestamp
: the time in seconds that should be used as the current time for all necessary comparisons.bearerPrefix
: (default: true) if false does not use 'Bearer ' token prefix.
fastify.jwt.secret
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.
reply.jwtSign(payload, [options,] callback)
request.jwtVerify([options,] callback)
These methods are very similar to their standard jsonwebtoken counterparts.
Example
const fastify = fastify fastify fastify fastify
Algorithms supported
The following algorithms are currently supported by jsonwebtoken that is internally used by fastify-jwt
.
algorithm(s) Parameter Value | Digital Signature or MAC Algorithm |
---|---|
HS256 | HMAC using SHA-256 hash algorithm |
HS384 | HMAC using SHA-384 hash algorithm |
HS512 | HMAC using SHA-512 hash algorithm |
RS256 | RSASSA using SHA-256 hash algorithm |
RS384 | RSASSA using SHA-384 hash algorithm |
RS512 | RSASSA 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 |
none | No digital signature or MAC value included |
Acknowledgements
This project is kindly sponsored by:
License
Licensed under MIT.