revocation.test.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var jwt = require('jsonwebtoken');
  2. var assert = require('assert');
  3. var expressjwt = require('../lib');
  4. var UnauthorizedError = require('../lib/errors/UnauthorizedError');
  5. describe('revoked jwts', function(){
  6. var secret = 'shhhhhh';
  7. var revoked_id = '1234'
  8. var middleware = expressjwt({
  9. secret: secret,
  10. algorithms: ['HS256'],
  11. isRevoked: function(req, payload, done){
  12. done(null, payload.jti && payload.jti === revoked_id);
  13. }
  14. });
  15. it('should throw if token is revoked', function(){
  16. var req = {};
  17. var res = {};
  18. var token = jwt.sign({ jti: revoked_id, foo: 'bar'}, secret);
  19. req.headers = {};
  20. req.headers.authorization = 'Bearer ' + token;
  21. middleware(req, res, function(err) {
  22. assert.ok(err);
  23. assert.equal(err.code, 'revoked_token');
  24. assert.equal(err.message, 'The token has been revoked.');
  25. });
  26. });
  27. it('should work if token is not revoked', function(){
  28. var req = {};
  29. var res = {};
  30. var token = jwt.sign({ jti: '1233', foo: 'bar'}, secret);
  31. req.headers = {};
  32. req.headers.authorization = 'Bearer ' + token;
  33. middleware(req, res, function() {
  34. assert.equal('bar', req.user.foo);
  35. });
  36. });
  37. it('should throw if error occurs checking if token is revoked', function(){
  38. var req = {};
  39. var res = {};
  40. var token = jwt.sign({ jti: revoked_id, foo: 'bar'}, secret);
  41. req.headers = {};
  42. req.headers.authorization = 'Bearer ' + token;
  43. expressjwt({
  44. secret: secret,
  45. algorithms: ['HS256'],
  46. isRevoked: function(req, payload, done){
  47. done(new Error('An error ocurred'));
  48. }
  49. })(req, res, function(err) {
  50. assert.ok(err);
  51. assert.equal(err.message, 'An error ocurred');
  52. });
  53. });
  54. });