verify.js 8.4 KB

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