使用mock-jwks测试Cognito JWKS时验证失败问题排查
解决mock-jwks测试Cognito JWKS验证失败的问题
从错误信息来看,有两个核心问题导致验证失败,逐个解决:
1. JWK的kid找不到
测试里创建mock-jwks时,第一个参数的issuer URL末尾多了个.,和token里的iss字段不匹配,导致mock的JWKS无法关联到生成的token。
2. 缺少token_use字段
Cognito的access token要求必须包含token_use: "access"字段,mock-jwks默认不会生成这个字段,需要手动添加。
另外还有两个细节问题:
- access token的
aud字段应该是Cognito的clientId(也就是verifier里的"123"),不是自定义域名 - 测试里的
jest.unmock('axios')会取消mock-jwks对JWKS请求的拦截,导致去真实请求AWS端点,必须去掉
修正后的Jest测试用例
import createJWKSMock from "mock-jwks"; import {authorizeFinance} from "@functions/auth-finance/handler"; describe('Authenticate finance', () => { // 去掉issuer URL末尾的点,和token里的iss保持一致 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: '123', // 改为verifier里的clientId iss: 'https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-xyz', token_use: 'access' // 添加Cognito要求的token_use字段 }); const event = { headers: { authorization: `Bearer ${token}`, } }; // 去掉jest.unmock('axios'),保留mock-jwks的拦截 const basicResponse = await authorizeFinance(event); // 若authLogic校验通过,调整期望结果为授权成功 expect(basicResponse).toEqual({ isAuthorized: true, context: {AuthInfo: 'Finance'} }); }); })
额外说明
如果你的authLogic有其他校验逻辑(比如特定用户组、权限),需要在生成token时添加对应的字段(比如cognito:groups),确保authLogic能返回true,测试才能匹配期望结果。
内容的提问来源于stack exchange,提问作者Interlated
相关产品推荐
相关产品推荐

