awslabs / aws-jwt-verify

JS library for verifying JWTs signed by Amazon Cognito, and any OIDC-compatible IDP that signs JWTs with RS256, RS384, RS512, ES256, ES384, and ES512
Apache License 2.0
632 stars 45 forks source link

How to use customJwtCheck with TypeScript and Custom Payload #146

Closed qoomon closed 1 year ago

qoomon commented 1 year ago

Question How to use customJwtCheck with TypeScript and Custom Payload?

Is there an easier approach than the following code? The main problem is that I can't access payload.sub if I don't cast the payload first.

// ...
customJwtCheck: ({header, payload: _payload, jwk}) => {
        const payload = _payload as GithubActionsJwtPayload
        if (!ALLOWED_GITHUB_PRINCIPALS.includes(payload.sub) {
            throw new FailedAssertionError(`Unexpected token sub`, payload.sub)
        }
    },
// ...
ottokruse commented 1 year ago

!ALLOWED_GITHUB_PRINCIPALS.includes(payload.sub as string) should work too and is slightly easier?

Or better:

if (typeof payload.sub !== "string" || !ALLOWED_GITHUB_PRINCIPALS.includes(payload.sub))

If you're using the CognitoJwtVerifier we should use the Cognito JWT typings instead of the generic ones, then you wouldn't need this cast. If you want to submit a PR? (Might be a bit of a rabbithole with the types though)