diff --git a/tests/jwt.test.ts b/tests/jwt.test.ts index 700eb6f..011e2d2 100644 --- a/tests/jwt.test.ts +++ b/tests/jwt.test.ts @@ -1,7 +1,7 @@ import { suite } from 'uvu' import { ServerResponse as Response } from 'http' import fs from 'fs' -import jsonwebtoken from 'jsonwebtoken' +import jsonwebtoken, { Algorithm } from 'jsonwebtoken' import expect from 'expect' import { jwt, Request } from '../src/index' @@ -15,14 +15,28 @@ it.before.each(() => { req.user = {} }) -it('should work if authorization header is valid jsonwebtoken', () => { +it('should work using default algorithm if authorization header is valid jsonwebtoken', () => { const secret = 'shhhhhh' const token = jsonwebtoken.sign({ foo: 'bar' }, secret) req.headers.authorization = 'Bearer ' + token jwt({ secret: secret })(req, res, () => { - expect('bar').toBe(req.user.foo) + expect(req.user.foo).toBe('bar') + }) +}) + +it('should work with different HMAC algorithms', () => { + const algorithms: Algorithm[] = ['HS512', 'HS256', 'HS384'] + const secret = 'shhhhhh' + + algorithms.forEach((algorithm) => { + const token = jsonwebtoken.sign({ foo: 'bar' }, secret, { algorithm }) + req.headers.authorization = 'Bearer ' + token + + jwt({ secret: secret, algorithm })(req, res, () => { + expect(req.user.foo).toBe('bar') + }) }) }) @@ -33,7 +47,7 @@ it('should work if authorization header is valid with a buffer secret', () => { req.headers.authorization = 'Bearer ' + token jwt({ secret: secret.toString(), algorithm: 'HS256' })(req, res, () => { - expect('bar').toBe(req.user.foo) + expect(req.user.foo).toBe('bar') }) }) @@ -44,7 +58,21 @@ it('should handle private key encryption', () => { req.headers.authorization = 'Bearer ' + jsonwebtoken.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }) jwt({ secret: [privateKey, publicKey], algorithm: 'RS256' })(req, res, () => { - expect('bar').toBe(req.user.foo) + expect(req.user.foo).toBe('bar') + }) +}) + +it('should work with different RSA algorithms', () => { + const algorithms: Algorithm[] = ['RS256', 'RS384', 'RS512'] + const privateKey = fs.readFileSync('tests/fixtures/private', { encoding: 'utf-8' }) + const publicKey = fs.readFileSync('tests/fixtures/public', { encoding: 'utf-8' }) + + algorithms.forEach((algorithm) => { + req.headers.authorization = 'Bearer ' + jsonwebtoken.sign({ foo: 'bar' }, privateKey, { algorithm }) + + jwt({ secret: [privateKey, publicKey], algorithm })(req, res, () => { + expect(req.user.foo).toBe('bar') + }) }) }) @@ -60,4 +88,12 @@ it('should not work with malformed input', () => { }) }) +it('should not work if authorization header is missing', () => { + const secret = 'shhhhhh' + + jwt({ secret: secret })(req, res, () => { + expect(req.user.foo).toBeUndefined() + }) +}) + it.run()