You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.5 KiB

  1. var jwt = require('../index');
  2. var expect = require('chai').expect;
  3. var assert = require('chai').assert;
  4. describe('HS256', function() {
  5. describe('when signing a token', function() {
  6. var secret = 'shhhhhh';
  7. var token = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'HS256' });
  8. it('should be syntactically valid', function() {
  9. expect(token).to.be.a('string');
  10. expect(token.split('.')).to.have.length(3);
  11. });
  12. it('should without options', function(done) {
  13. var callback = function(err, decoded) {
  14. assert.ok(decoded.foo);
  15. assert.equal('bar', decoded.foo);
  16. done();
  17. };
  18. callback.issuer = "shouldn't affect";
  19. jwt.verify(token, secret, callback );
  20. });
  21. it('should validate with secret', function(done) {
  22. jwt.verify(token, secret, function(err, decoded) {
  23. assert.ok(decoded.foo);
  24. assert.equal('bar', decoded.foo);
  25. done();
  26. });
  27. });
  28. it('should throw with invalid secret', function(done) {
  29. jwt.verify(token, 'invalid secret', function(err, decoded) {
  30. assert.isUndefined(decoded);
  31. assert.isNotNull(err);
  32. done();
  33. });
  34. });
  35. it('should throw with secret and token not signed', function(done) {
  36. var signed = jwt.sign({ foo: 'bar' }, secret, { algorithm: 'none' });
  37. var unsigned = signed.split('.')[0] + '.' + signed.split('.')[1] + '.';
  38. jwt.verify(unsigned, 'secret', function(err, decoded) {
  39. assert.isUndefined(decoded);
  40. assert.isNotNull(err);
  41. done();
  42. });
  43. });
  44. it('should throw when verifying null', function(done) {
  45. jwt.verify(null, 'secret', function(err, decoded) {
  46. assert.isUndefined(decoded);
  47. assert.isNotNull(err);
  48. done();
  49. });
  50. });
  51. it('should return an error when the token is expired', function(done) {
  52. var token = jwt.sign({ exp: 1 }, secret, { algorithm: 'HS256' });
  53. jwt.verify(token, secret, { algorithm: 'HS256' }, function(err, decoded) {
  54. assert.isUndefined(decoded);
  55. assert.isNotNull(err);
  56. done();
  57. });
  58. });
  59. it('should NOT return an error when the token is expired with "ignoreExpiration"', function(done) {
  60. var token = jwt.sign({ exp: 1, foo: 'bar' }, secret, { algorithm: 'HS256' });
  61. jwt.verify(token, secret, { algorithm: 'HS256', ignoreExpiration: true }, function(err, decoded) {
  62. assert.ok(decoded.foo);
  63. assert.equal('bar', decoded.foo);
  64. assert.isNull(err);
  65. done();
  66. });
  67. });
  68. });
  69. });