awslabs / aws-jwt-verify

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

How to use customJwtCheck with TypeScript and Custom Payload #146

Closed qoomon closed 8 months ago

qoomon commented 8 months 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 8 months 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)