@yingyeothon/lambda-authorizer-jwt
v2.0.1
Published
JWT-issuing and JWT-verifying AWS API Gateway custom authorizers, including the REQUEST authorizer a WebSocket $connect route requires.
Readme
@yingyeothon/lambda-authorizer-jwt
JWT-based AWS API Gateway custom authorizers built on @yingyeothon/lambda-authorizer. Invalid logins and unknown schemes produce a Deny policy, while invalid, expired, or malformed JWTs raise Unauthorized (HTTP 401).
createJwtAuthorizer— a TOKEN authorizer for REST APIs.Basicis checked against yourlogincallback and, on success, a freshly signed JWT is returned as the context valuetoken;Beareris verified and its claims published throughbuildContext.createJwtRequestAuthorizer— a REQUEST authorizer that verifies only. This is the one to attach to a WebSocket API's$connectroute, because a WebSocket API supports no other Lambda authorizer type. It never issues: a handshake has no response body to hand a token back through, so keep the login exchange behind a REST endpoint usingcreateJwtAuthorizer.
Install
npm install @yingyeothon/lambda-authorizer-jwtUsage
ESM:
import { createJwtAuthorizer } from "@yingyeothon/lambda-authorizer-jwt";
export const handler = createJwtAuthorizer({
jwtSecret: process.env.JWT_SECRET!,
jwtExpiresIn: "30m",
buildJWTPayload: ({ id }) => ({ id }),
login: async ({ id, password }) => checkCredentials(id, password),
});CJS:
const { createJwtAuthorizer } = require("@yingyeothon/lambda-authorizer-jwt");
exports.handler = createJwtAuthorizer({
jwtSecret: process.env.JWT_SECRET,
login: async ({ id, password }) => checkCredentials(id, password),
});After a successful Basic login the issued JWT is available to downstream integrations as the authorizer context value token; clients then send it back as Authorization: Bearer <token>.
Verifying on a WebSocket $connect
import { createJwtRequestAuthorizer } from "@yingyeothon/lambda-authorizer-jwt";
export const handler = createJwtRequestAuthorizer({
jwtSecret: process.env.JWT_SECRET_KEY!,
verifyOptions: { issuer: "yyt-lobby", audience: "instant-dungeon" },
});A browser cannot set an Authorization header on a WebSocket handshake, so the default sources also accept new WebSocket(url, ["bearer", token]), which arrives as Sec-WebSocket-Protocol: bearer, <token>. Your $connect integration must echo the selected subprotocol back or the browser aborts the handshake — see handleConnect's selectSubprotocol in @yingyeothon/lambda-gamebase.
Pin issuer and audience. A valid signature only proves the token was minted by a holder of the secret; it says nothing about which deployment it was minted for. With a shared symmetric secret, every holder of that secret can mint any identity, so the secret is a signing capability and not merely a verification key — treat it accordingly.
Set the API Gateway authorizer's result cache TTL to 0. $connect runs once per connection, so caching buys nothing and lets an allow outlive the token's expiry. Revocation after the handshake is not the authorizer's job either: an established connection is dropped by the application, not by a policy.
Context
buildContext turns verified claims into the policy context. The default, memberIdFromSubject, publishes { memberId: claims.sub } — falling back to claims.id, which is what this package's own buildJWTPayload default issues — and nothing else. That value also becomes the policy's principalId.
An empty context is a refusal. If buildContext returns {}, the token is denied rather than allowed with no identity: an authorizer whose job is to establish who is calling must not say yes when it established nobody. So a correctly signed token carrying no subject claim does not get through.
A token with no exp claim is denied too, since a bearer credential that never expires cannot be timed out — pass requireExpiry: false if you genuinely want one.
The context is deliberately narrow. API Gateway only carries string, number, and boolean values there, and $context.authorizer.* can be configured into access logs, so a verified token is never placed in it.
The one exception is createJwtAuthorizer's Basic exchange, which returns the JWT it just issued as context.token — that is the only way the caller receives it. On an API using that exchange, a live credential is reachable through $context.authorizer.token: do not write the authorizer context into access logs there.
Public API
createJwtAuthorizer(options)— builds anAPIGatewayTokenAuthorizerHandlerfromJwtAuthorizerOptions.createJwtRequestAuthorizer(options)— builds anAPIGatewayRequestAuthorizerHandlerfromJwtRequestAuthorizerOptions.memberIdFromSubject(claims)— the defaultbuildContext:{ memberId: sub ?? id }, or{}.JwtAuthorizerOptions(type) —{ jwtSecret, jwtExpiresIn?, buildJWTPayload?, buildContext?, verifyOptions?, requireExpiry?, login, logger? }. Defaults:jwtExpiresIn: "30m",buildJWTPayload: ({ id }) => ({ id }),buildContext: memberIdFromSubject,requireExpiry: true.JwtRequestAuthorizerOptions(type) —{ jwtSecret, verifyOptions?, buildContext?, requireExpiry?, sources?, onError?, logger? }. Same defaults.BuildAuthorizerContext(type) —(claims: JwtPayload) => APIGatewayAuthorizerResultContext.
Migrating from the legacy package
- The npm package was renamed:
@yingyeothon/aws-lambda-jwt-custom-authorizer→@yingyeothon/lambda-authorizer-jwt(and its base package@yingyeothon/aws-lambda-custom-authorizer→@yingyeothon/lambda-authorizer). buildJWTAuthorizer→createJwtAuthorizer, and its options typeJWTAuthorizerArguments(legacyIJWTAuthorizerArguments) →JwtAuthorizerOptions.- The default export is gone: use the named export
createJwtAuthorizer. jsonwebtokenwas upgraded from v8 to v9. Verification semantics are unchanged for this package (invalid signature, expired, and malformed tokens all still yieldUnauthorized), butjwtExpiresInis now typed asSignOptions["expiresIn"](a number of seconds or anms-style string such as"30m"), andbuildJWTPayloadis a plain function returningstring | Buffer | objectinstead of a generic.- The
loggeryou pass is now also used by the underlying authorizer, so verification errors are logged beforeUnauthorizedis thrown (the legacy version silently discarded them). It no longer logs the credential id, the decoded claims, or the issued policy context. - A verified
Bearerno longer echoes the token back as the context valuetoken. The context is now built from the claims ({ memberId }by default); passbuildContextto shape it. TheBasicexchange still returns{ token }, because that is the only way the caller receives the JWT it just earned. createJwtRequestAuthorizeris new. The legacy package built only a TOKEN authorizer, which a WebSocket API cannot use.- A verified token must now yield an identity and an expiry: an empty
buildContextresult or a missingexpdenies rather than allows.requireExpiry: falserestores the old expiry behaviour; there is no opt-out for the identity check. - A verified token's subject becomes the policy
principalId.
