UNPKG

1.97 kBPlain TextView Raw
1import * as jwt from 'jsonwebtoken';
2import * as express from 'express';
3import { expressjwt, ExpressJwtRequest } from '../src';
4import assert from 'assert';
5
6describe('revoked jwts', function () {
7 const secret = 'shhhhhh';
8
9 const revoked_id = '1234'
10
11 const middleware = expressjwt({
12 secret: secret,
13 algorithms: ['HS256'],
14 isRevoked: async (req, token) => {
15 const isRevoked = typeof token.payload !== 'string' &&
16 token.payload.jti === revoked_id;
17 return isRevoked;
18 }
19 });
20
21 it('should throw if token is revoked', function () {
22 const req = {} as ExpressJwtRequest;
23 const res = {} as express.Response;
24
25 const token = jwt.sign({ jti: revoked_id, foo: 'bar' }, secret);
26
27 req.headers = {};
28 req.headers.authorization = 'Bearer ' + token;
29
30 middleware(req, res, function (err) {
31 assert.ok(err);
32 assert.equal(err.code, 'revoked_token');
33 assert.equal(err.message, 'The token has been revoked.');
34 });
35 });
36
37 it('should work if token is not revoked', function () {
38 const req = {} as ExpressJwtRequest;
39 const res = {} as express.Response;
40
41 const token = jwt.sign({ jti: '1233', foo: 'bar' }, secret);
42
43 req.headers = {};
44 req.headers.authorization = 'Bearer ' + token;
45
46 middleware(req, res, function () {
47 assert.equal(req.auth.foo, 'bar');
48 });
49 });
50
51 it('should throw if error occurs checking if token is revoked', function (done) {
52 const req = {} as ExpressJwtRequest;
53 const res = {} as express.Response;
54
55 const token = jwt.sign({ jti: revoked_id, foo: 'bar' }, secret);
56
57 req.headers = {};
58 req.headers.authorization = 'Bearer ' + token;
59
60 expressjwt({
61 secret: secret,
62 algorithms: ['HS256'],
63 isRevoked: async () => {
64 throw new Error('An error ocurred');
65 }
66 })(req, res, function (err) {
67 assert.ok(err);
68 assert.equal(err.message, 'An error ocurred');
69 done();
70 });
71 });
72});