multitenancy.test.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var jwt = require('jsonwebtoken');
  2. var assert = require('assert');
  3. var expressjwt = require('../lib');
  4. var UnauthorizedError = require('../lib/errors/UnauthorizedError');
  5. describe('multitenancy', function(){
  6. var req = {};
  7. var res = {};
  8. var tenants = {
  9. 'a': {
  10. secret: 'secret-a'
  11. }
  12. };
  13. var secretCallback = function(req, payload, cb){
  14. var issuer = payload.iss;
  15. if (tenants[issuer]){
  16. return cb(null, tenants[issuer].secret);
  17. }
  18. return cb(new UnauthorizedError('missing_secret',
  19. { message: 'Could not find secret for issuer.' }));
  20. };
  21. var middleware = expressjwt({
  22. secret: secretCallback,
  23. algorithms: ['HS256']
  24. });
  25. it ('should retrieve secret using callback', function(){
  26. var token = jwt.sign({ iss: 'a', foo: 'bar'}, tenants.a.secret);
  27. req.headers = {};
  28. req.headers.authorization = 'Bearer ' + token;
  29. middleware(req, res, function() {
  30. assert.equal('bar', req.user.foo);
  31. });
  32. });
  33. it ('should throw if an error ocurred when retrieving the token', function(){
  34. var secret = 'shhhhhh';
  35. var token = jwt.sign({ iss: 'inexistent', foo: 'bar'}, secret);
  36. req.headers = {};
  37. req.headers.authorization = 'Bearer ' + token;
  38. middleware(req, res, function(err) {
  39. assert.ok(err);
  40. assert.equal(err.code, 'missing_secret');
  41. assert.equal(err.message, 'Could not find secret for issuer.');
  42. });
  43. });
  44. it ('should fail if token is revoked', function(){
  45. var token = jwt.sign({ iss: 'a', foo: 'bar'}, tenants.a.secret);
  46. req.headers = {};
  47. req.headers.authorization = 'Bearer ' + token;
  48. expressjwt({
  49. secret: secretCallback,
  50. algorithms: ['HS256'],
  51. isRevoked: function(req, payload, done){
  52. done(null, true);
  53. }
  54. })(req, res, function(err) {
  55. assert.ok(err);
  56. assert.equal(err.code, 'revoked_token');
  57. assert.equal(err.message, 'The token has been revoked.');
  58. });
  59. });
  60. });