Skip to content

feat: Implement JWT signing and verification middleware#5

Open
charliewwdev wants to merge 4 commits intomainfrom
feat/implement-jwt-signing-and-verification-middleware
Open

feat: Implement JWT signing and verification middleware#5
charliewwdev wants to merge 4 commits intomainfrom
feat/implement-jwt-signing-and-verification-middleware

Conversation

@charliewwdev
Copy link
Copy Markdown
Member

Create middleware that signs JWTs using RS256 (asymmetric), validates signatures on incoming requests, and rejects malformed or expired tokens with appropriate 401 responses.


Generated by OpenDev AI

RS256 JWT implemented entirely with Node's built-in crypto module — no third-party JWT library added, keeping the dependency footprint minimal.

jwt.ts — core primitives:

  • signToken builds header.payload.signature using createSign('RSA-SHA256'). The iat claim is always stamped; exp/iss/aud/sub are added from SignOptions.
  • verifyToken checks: 3-part structure → alg lock (RS256 only, prevents algorithm substitution attacks) → RSA signature → exp/nbf (with optional clockSkew tolerance) → iss/aud claims. Each failure raises a JwtError with a typed code so callers can distinguish expired tokens from forged ones.
  • base64url encode/decode uses Node's native Buffer.toString('base64url') (Node 16+) and a manual decode path that restores standard base64 padding.

auth.ts — HTTP middleware:

  • createAuthMiddleware(publicKey, options) returns a standard (req, res, next) middleware compatible with Express, raw node:http, and Hono adapters.
  • Default token extraction parses Authorization: Bearer <token> strictly (rejects other schemes).
  • A custom tokenExtractor can be supplied (e.g. cookie-based auth).
  • On success: decoded token is attached to req.auth as AuthenticatedRequest.
  • On any JWT failure: 401 with JSON body { error, reason } and WWW-Authenticate: Bearer realm="opendev" header. Unexpected errors are forwarded to next(err) so the outer error handler can log/report them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant