diff --git a/.jshintrc b/.jshintrc index e0b1f93..0f9fef3 100644 --- a/.jshintrc +++ b/.jshintrc @@ -15,6 +15,7 @@ "it": true, "require": true, "atob": false, - "escape": true + "escape": true, + "before": true } } \ No newline at end of file diff --git a/index.js b/index.js index 442fd50..7bd3d2d 100644 --- a/index.js +++ b/index.js @@ -107,6 +107,12 @@ module.exports.verify = function(jwtString, secretOrPublicKey, options, callback return done(new JsonWebTokenError('jwt signature is required')); } + if (!options.algorithms) { + options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') ? + [ 'RS256','RS384','RS512','ES256','ES384','ES512' ] : + [ 'HS256','HS384','HS512' ]; + } + var valid; try { @@ -126,6 +132,11 @@ module.exports.verify = function(jwtString, secretOrPublicKey, options, callback return done(err); } + var header = jws.decode(jwtString).header; + if (!~options.algorithms.indexOf(header.alg)) { + return done(new JsonWebTokenError('invalid signature')); + } + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { if (typeof payload.exp !== 'number') { return done(new JsonWebTokenError('invalid exp value')); diff --git a/test/wrong_alg.tests.js b/test/wrong_alg.tests.js new file mode 100644 index 0000000..513ba18 --- /dev/null +++ b/test/wrong_alg.tests.js @@ -0,0 +1,20 @@ +var fs = require('fs'); +var path = require('path'); +var jwt = require('../index'); +var JsonWebTokenError = require('../lib/JsonWebTokenError'); +var expect = require('chai').expect; + + +var pub = fs.readFileSync(path.join(__dirname, 'pub.pem'), 'utf8'); +// priv is never used +// var priv = fs.readFileSync(path.join(__dirname, 'priv.pem')); + +var TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE0MjY1NDY5MTl9.ETgkTn8BaxIX4YqvUWVFPmum3moNZ7oARZtSBXb_vP4'; + +describe('signing with pub key as symmetric', function () { + it('should not verify', function () { + expect(function () { + jwt.verify(TOKEN, pub); + }).to.throw(JsonWebTokenError, /invalid signature/); + }); +}); \ No newline at end of file