Configure dynamic keys with secretOrKeyProvider
masterIf you need to manage secrets or keys dynamically (e.g., fetching them from a database or vault), use the secretOrKeyProvider option. This function takes precedence over static secret, publicKey, or privateKey options.
Note: If you use an asynchronous version of secretOrKeyProvider, you must use the asynchronous .signAsync() and .verifyAsync() methods of JwtService. Using synchronous methods with an async provider will throw an exception.
JwtModule.register({
/* Secret has precedence over keys */
secret: 'hard!to-guess_secret',
/* public key used in asymmetric algorithms (required if non other secrets present) */
publicKey: '...',
/* private key used in asymmetric algorithms (required if non other secrets present) */
privateKey: '...',
/* Dynamic key provider has precedence over static secret or pub/private keys */
secretOrKeyProvider: (
requestType: JwtSecretRequestType,
tokenOrPayload: string | Object | Buffer,
verifyOrSignOrOptions?: jwt.VerifyOptions | jwt.SignOptions
) => {
switch (requestType) {
case JwtSecretRequestType.SIGN:
// retrieve signing key dynamically
return 'privateKey';
case JwtSecretRequestType.VERIFY:
// retrieve public key for verification dynamically
return 'publicKey';
default:
// retrieve secret dynamically
return 'hard!to-guess_secret';
}
},
});