Testing Cognito JWKS using mock-jwk?

Viewed 19

Auth AWS lambda

export const authorizeFinance = async (event) => {
    if (event.headers.authorization) {
        const token = event.headers.authorization.substring(7);
        try {
            const verifier = CognitoJwtVerifier.create({
                userPoolId: "xyz",
                tokenUse: "access",
                clientId: "123",
            });
            const payload = await verifier.verify(token);
            if (authLogic(payload)) {
                return {isAuthorized: true, context: {AuthInfo: 'Finance'}}
            }
            return {isAuthorized: false, context: {}}
        } catch (e) {
            return {isAuthorized: false, context: {}}
        }
    }
}

Test case in jest using mock-jwks

import createJWKSMock from "mock-jwks";
import {authorizeFinance} from "@functions/auth-finance/handler";

describe('Authenticate finance', () => {
  const jwks = createJWKSMock('https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-xyz.', 'well-known/jwks.json');

  beforeEach(() => {
    jwks.start();
  });

  afterEach(() => {
    jwks.stop();
  });


  test('should verify the token', async () => {
    const token = jwks.token({
        aud: 'https://test.auth-domain.com/',
        iss: 'https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-xyz',
    });
    console.log(token);
    const event = {
        headers: {
            authorization: `Bearer ${token}`,
        }
    };
    jest.unmock('axios');
    const basicResponse = await authorizeFinance(event);
    console.log('jatin', basicResponse);
    expect(basicResponse).toEqual({ isAuthorized: false, context: {} });
  });
})

Fails

Authentication failed JWK for kid "BlYCji0Uj6V3LAxmK1JHqYgnPJIUUqeiS8YzUf0vfh0=" not found in the JWKS
Authentication failed Missing Token use. Expected one of: id, access
0 Answers
Related