koa-jwt2 is Koa middleware designed for authenticating HTTP requests using JSON Web Tokens (JWT). It validates incoming JWTs and populates `ctx.state.user` (or a configurable property) with the decoded payload, making it available for subsequent middleware to handle authorization and access control. Key features include support for `audience`, `issuer`, and `expiration` validation, handling of base64 URL-encoded secrets, and verification with public/private key pairs. It integrates `koa-unless` for specifying unprotected paths and offers advanced options like custom token extraction via `getToken` and multi-tenancy support through an asynchronous secret function. The current stable version is 1.0.3. However, the package's GitHub repository has been archived, indicating it is no longer actively maintained, and thus its release cadence is effectively ceased. This makes it distinct from more actively developed alternatives, though its multi-tenancy secret resolution feature remains notable.
npm install koa-jwt2Verified import paths — ran on the pinned version, not inferred.
This quickstart sets up a basic Koa application with two routes: `/token` to issue a JWT and `/protected` which is secured by `koa-jwt2`. It demonstrates how to configure the middleware with a secret, access the decoded user payload from `ctx.state.user`, and use the `unless` option to exclude the token issuance route from JWT validation. It requires `@koa/router` and `jsonwebtoken`.
Consider migrating to actively maintained alternatives like `koa-jwt` (ensure you check its maintenance status) or other modern Koa authentication solutions.
For base64, use `secret: Buffer.from('your-base64-secret', 'base64')`. For public keys, use `secret: fs.readFileSync('/path/to/public.pub')`.Use the `property` option to specify an alternative key, e.g., `jwt({ secret: '...', property: 'auth' })`, then access `ctx.state.auth`.Ensure that if `credentialsRequired: false` is used, all downstream middleware and route handlers properly check for the presence and validity of `ctx.state.user` before granting access to sensitive resources or performing authenticated actions. Implement explicit authorization checks.
Wrap asynchronous operations in `try...catch` blocks within the `secret` function and handle specific error types, potentially resolving with `null` or a default secret if appropriate for the application's security model, or re-throwing custom errors that can be caught by a more specific Koa error handler.
Ensure you are using `const jwt = require('koa-jwt2');` as this package is primarily CommonJS. If using `type: 'module'` in `package.json`, you might need to use `import jwt from 'koa-jwt2'` if a default export is provided, but this specific package's primary usage is CJS.Verify the token's validity (signature, expiry, claims like audience/issuer). Check that the token is sent in the `Authorization: Bearer <token>` header, or configure `getToken` if it's in a query parameter or cookie. Ensure the `secret` configured matches the secret used to sign the token.
Review the logic within your `secret` async function. Ensure that `data.getTenantByIdentifier` or equivalent logic correctly retrieves a tenant and its secret, and that any `reject(new Error('missing_secret'))` paths are intended and handled. Debug the `payload.iss` value to confirm it matches expected issuer identifiers.Double-check the `secret` configuration. Ensure the string secret is identical, or that the `Buffer` for a base64 secret or public key is loaded correctly and contains the exact bytes. Verify that no encoding issues are corrupting the key or secret.