From 72236ec1cfb0e7847351c83908be1d84141e30f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=C2=A0F=2E=20Romaniello?= Date: Wed, 20 Apr 2022 09:34:04 -0300 Subject: [PATCH] add support for async, closes #249 --- src/index.ts | 4 ++-- test/jwt.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 50316892..17221466 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,7 @@ import { UnauthorizedError } from './errors/UnauthorizedError'; export type GetVerificationKey = (req: express.Request, token: jwt.Jwt | undefined) => Promise; export type IsRevoked = (req: express.Request, token: jwt.Jwt | undefined) => Promise; -type TokenGetter = (req: express.Request) => string | undefined; +type TokenGetter = (req: express.Request) => string | Promise | undefined; type Params = { secret: jwt.Secret | GetVerificationKey, @@ -48,7 +48,7 @@ export const expressjwt = (options: Params) => { } if (options.getToken && typeof options.getToken === 'function') { - token = options.getToken(req); + token = await options.getToken(req); } else if (req.headers && req.headers.authorization) { const parts = req.headers.authorization.split(' '); if (parts.length == 2) { diff --git a/test/jwt.test.ts b/test/jwt.test.ts index 8b11f23b..07f9a917 100644 --- a/test/jwt.test.ts +++ b/test/jwt.test.ts @@ -322,6 +322,30 @@ describe('work tests', function () { }); }); + it('should work with an async getToken function', function (done) { + const req = {} as ExpressJwtRequest; + const res = {} as express.Response; + const secret = 'shhhhhh'; + const token = jwt.sign({ foo: 'bar' }, secret); + + req.headers = {}; + req.query = {}; + req.query.token = token; + + function getTokenFromQuery(req) { + return Promise.resolve(req.query.token); + } + + expressjwt({ + secret: secret, + algorithms: ['HS256'], + getToken: getTokenFromQuery + })(req, res, function () { + assert.equal(req.auth.foo, 'bar'); + done(); + }); + }); + it('should work with a secretCallback function that accepts header argument', function (done) { const req = {} as ExpressJwtRequest; const res = {} as express.Response;