verify.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. var JsonWebTokenError = require('./lib/JsonWebTokenError');
  2. var NotBeforeError = require('./lib/NotBeforeError');
  3. var TokenExpiredError = require('./lib/TokenExpiredError');
  4. var decode = require('./decode');
  5. var timespan = require('./lib/timespan');
  6. var PS_SUPPORTED = require('./lib/psSupported');
  7. var jws = require('jws');
  8. var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512'];
  9. var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512'];
  10. var HS_ALGS = ['HS256', 'HS384', 'HS512'];
  11. if (PS_SUPPORTED) {
  12. PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');
  13. RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512');
  14. }
  15. module.exports = function (jwtString, secretOrPublicKey, options, callback) {
  16. if ((typeof options === 'function') && !callback) {
  17. callback = options;
  18. options = {};
  19. }
  20. if (!options) {
  21. options = {};
  22. }
  23. //clone this object since we are going to mutate it.
  24. options = Object.assign({}, options);
  25. var done;
  26. if (callback) {
  27. done = callback;
  28. } else {
  29. done = function(err, data) {
  30. if (err) throw err;
  31. return data;
  32. };
  33. }
  34. if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') {
  35. return done(new JsonWebTokenError('clockTimestamp must be a number'));
  36. }
  37. if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) {
  38. return done(new JsonWebTokenError('nonce must be a non-empty string'));
  39. }
  40. var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000);
  41. if (!jwtString){
  42. return done(new JsonWebTokenError('jwt must be provided'));
  43. }
  44. if (typeof jwtString !== 'string') {
  45. return done(new JsonWebTokenError('jwt must be a string'));
  46. }
  47. var parts = jwtString.split('.');
  48. if (parts.length !== 3){
  49. return done(new JsonWebTokenError('jwt malformed'));
  50. }
  51. var decodedToken;
  52. try {
  53. decodedToken = decode(jwtString, { complete: true });
  54. } catch(err) {
  55. return done(err);
  56. }
  57. if (!decodedToken) {
  58. return done(new JsonWebTokenError('invalid token'));
  59. }
  60. var header = decodedToken.header;
  61. var getSecret;
  62. if(typeof secretOrPublicKey === 'function') {
  63. if(!callback) {
  64. return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback'));
  65. }
  66. getSecret = secretOrPublicKey;
  67. }
  68. else {
  69. getSecret = function(header, secretCallback) {
  70. return secretCallback(null, secretOrPublicKey);
  71. };
  72. }
  73. return getSecret(header, function(err, secretOrPublicKey) {
  74. if(err) {
  75. return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message));
  76. }
  77. var hasSignature = parts[2].trim() !== '';
  78. if (!hasSignature && secretOrPublicKey){
  79. return done(new JsonWebTokenError('jwt signature is required'));
  80. }
  81. if (hasSignature && !secretOrPublicKey) {
  82. return done(new JsonWebTokenError('secret or public key must be provided'));
  83. }
  84. if (!hasSignature && !options.algorithms) {
  85. options.algorithms = ['none'];
  86. }
  87. if (!options.algorithms) {
  88. options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') ||
  89. ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS :
  90. ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS;
  91. }
  92. if (!~options.algorithms.indexOf(decodedToken.header.alg)) {
  93. return done(new JsonWebTokenError('invalid algorithm'));
  94. }
  95. var valid;
  96. try {
  97. valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey);
  98. } catch (e) {
  99. return done(e);
  100. }
  101. if (!valid) {
  102. return done(new JsonWebTokenError('invalid signature'));
  103. }
  104. var payload = decodedToken.payload;
  105. if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {
  106. if (typeof payload.nbf !== 'number') {
  107. return done(new JsonWebTokenError('invalid nbf value'));
  108. }
  109. if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {
  110. return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
  111. }
  112. }
  113. if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {
  114. if (typeof payload.exp !== 'number') {
  115. return done(new JsonWebTokenError('invalid exp value'));
  116. }
  117. if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {
  118. return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));
  119. }
  120. }
  121. if (options.audience) {
  122. var audiences = Array.isArray(options.audience) ? options.audience : [options.audience];
  123. var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
  124. var match = target.some(function (targetAudience) {
  125. return audiences.some(function (audience) {
  126. return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;
  127. });
  128. });
  129. if (!match) {
  130. return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));
  131. }
  132. }
  133. if (options.issuer) {
  134. var invalid_issuer =
  135. (typeof options.issuer === 'string' && payload.iss !== options.issuer) ||
  136. (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);
  137. if (invalid_issuer) {
  138. return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));
  139. }
  140. }
  141. if (options.subject) {
  142. if (payload.sub !== options.subject) {
  143. return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));
  144. }
  145. }
  146. if (options.jwtid) {
  147. if (payload.jti !== options.jwtid) {
  148. return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));
  149. }
  150. }
  151. if (options.nonce) {
  152. if (payload.nonce !== options.nonce) {
  153. return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce));
  154. }
  155. }
  156. if (options.maxAge) {
  157. if (typeof payload.iat !== 'number') {
  158. return done(new JsonWebTokenError('iat required when maxAge is specified'));
  159. }
  160. var maxAgeTimestamp = timespan(options.maxAge, payload.iat);
  161. if (typeof maxAgeTimestamp === 'undefined') {
  162. return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
  163. }
  164. if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {
  165. return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000)));
  166. }
  167. }
  168. if (options.complete === true) {
  169. var signature = decodedToken.signature;
  170. return done(null, {
  171. header: header,
  172. payload: payload,
  173. signature: signature
  174. });
  175. }
  176. return done(null, payload);
  177. });
  178. };