Skip to content

Commit

Permalink
add support for async, closes #249
Browse files Browse the repository at this point in the history
  • Loading branch information
jfromaniello committed Apr 20, 2022
1 parent cb50ed4 commit 72236ec
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { UnauthorizedError } from './errors/UnauthorizedError';
export type GetVerificationKey = (req: express.Request, token: jwt.Jwt | undefined) => Promise<jwt.Secret>;
export type IsRevoked = (req: express.Request, token: jwt.Jwt | undefined) => Promise<boolean>;

type TokenGetter = (req: express.Request) => string | undefined;
type TokenGetter = (req: express.Request) => string | Promise<string> | undefined;

type Params = {
secret: jwt.Secret | GetVerificationKey,
Expand Down Expand Up @@ -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) {
Expand Down
24 changes: 24 additions & 0 deletions test/jwt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 72236ec

Please sign in to comment.