Skip to content

Commit

Permalink
Add logic to JWT.verify to validate JWT is not expired (#366)
Browse files Browse the repository at this point in the history
* Add logic to jwt.verify to validate jwt is not expired

* Update test
  • Loading branch information
kirahsapong authored Jan 11, 2024
1 parent 8eac115 commit ddc302a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/credentials/src/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,10 @@ export class Jwt {
static async verify(options: VerifyJwtOptions): Promise<JwtVerifyResult> {
const { decoded: decodedJwt, encoded: encodedJwt } = Jwt.parse({ jwt: options.jwt });

if (decodedJwt.payload.exp && Math.floor(Date.now() / 1000) > decodedJwt.payload.exp) {
throw new Error(`Verification failed: JWT is expired`);
}

// TODO: should really be looking for verificationMethod with authentication verification relationship
const dereferenceResult = await Jwt.didResolver.dereference({ didUrl: decodedJwt.header.kid! });
if (dereferenceResult.dereferencingMetadata.error) {
Expand Down
15 changes: 15 additions & 0 deletions packages/credentials/tests/jwt.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,21 @@ describe('Jwt', () => {
});

describe('verify()', () => {
it('throws error if JWT is expired', async () => {
const did = await DidKeyMethod.create({ keyAlgorithm: 'secp256k1' });
const header: JwtHeaderParams = { typ: 'JWT', alg: 'ES256K', kid: did.document.verificationMethod![0].id };
const base64UrlEncodedHeader = Convert.object(header).toBase64Url();

const payload: JwtPayload = { exp: Math.floor(Date.now() / 1000 - 1) };
const base64UrlEncodedPayload = Convert.object(payload).toBase64Url();

try {
await Jwt.verify({ jwt: `${base64UrlEncodedHeader}.${base64UrlEncodedPayload}.hijk` });
expect.fail();
} catch(e: any) {
expect(e.message).to.include('JWT is expired');
}
});
it('throws error if JWT header kid does not dereference a verification method', async () => {
const did = await DidKeyMethod.create({ keyAlgorithm: 'secp256k1' });
const header: JwtHeaderParams = { typ: 'JWT', alg: 'ES256K', kid: did.did };
Expand Down

0 comments on commit ddc302a

Please sign in to comment.