UNPKG

1.99 kBPlain TextView Raw
1import * as jwt from 'jsonwebtoken';
2import * as express from 'express';
3import { expressjwt, ExpressJwtRequest, GetVerificationKey } from '../src';
4import assert from 'assert';
5
6describe('multitenancy', function () {
7 const req = {} as ExpressJwtRequest;
8 const res = {} as express.Response;
9
10 const tenants = {
11 'a': {
12 secret: 'secret-a'
13 }
14 };
15
16 const secretCallback: GetVerificationKey = function (req, token) {
17 const issuer = (token.payload as jwt.JwtPayload).iss;
18 if (tenants[issuer]) {
19 return tenants[issuer].secret;
20 }
21 throw new Error('Could not find secret for issuer.');
22 };
23
24 const middleware = expressjwt({
25 secret: secretCallback,
26 algorithms: ['HS256']
27 });
28
29 it('should retrieve secret using callback', function (done) {
30 const token = jwt.sign({ foo: 'bar' }, tenants.a.secret, { issuer: 'a' });
31
32 req.headers = {};
33 req.headers.authorization = 'Bearer ' + token;
34
35 middleware(req, res, function () {
36 assert.equal(req.auth.foo, 'bar');
37 done();
38 });
39 });
40
41 it('should throw if an error ocurred when retrieving the token', function (done) {
42 const secret = 'shhhhhh';
43 const token = jwt.sign({ iss: 'inexistent', foo: 'bar' }, secret);
44
45 req.headers = {};
46 req.headers.authorization = 'Bearer ' + token;
47
48 middleware(req, res, function (err) {
49 assert.ok(err);
50 assert.equal(err.message, 'Could not find secret for issuer.');
51 done();
52 });
53 });
54
55 it('should fail if token is revoked', function (done) {
56 const token = jwt.sign({ iss: 'a', foo: 'bar' }, tenants.a.secret);
57
58 req.headers = {};
59 req.headers.authorization = 'Bearer ' + token;
60
61 expressjwt({
62 secret: secretCallback,
63 algorithms: ['HS256'],
64 isRevoked: async () => true
65 })(req, res, function (err) {
66 assert.ok(err);
67 assert.equal(err.code, 'revoked_token');
68 assert.equal(err.message, 'The token has been revoked.');
69 done();
70 });
71 });
72});
73