Koa Bearer Token Middleware

raw JSON →
2.0.2 verified Thu Apr 23 auth: no javascript maintenance

koa-bearer-token is a middleware for Koa.js that parses bearer tokens from incoming requests, adhering to RFC6750. It extracts tokens from the `Authorization: Bearer <token>` header, `access_token` query parameter, or `access_token` in the request body. Since version 2.0.0, it also supports extracting tokens from signed or unsigned cookies. The current stable version is 2.0.2, released in August 2021, suggesting a maintenance or slow-cadence release schedule. Key differentiators include its strict RFC6750 compliance, extensive configurability for token keys and locations, and built-in TypeScript support. It integrates seamlessly with Koa applications, making it straightforward to secure API endpoints with OAuth2 bearer tokens. It requires Node.js version 12 or higher.

error TypeError: (0, _koaBearertoken.default) is not a function
cause Attempting to import `koa-bearer-token` using a default import syntax in ESM after v2.0.0.
fix
Change the import statement from import bearerToken from 'koa-bearer-token'; to import { bearerToken } from 'koa-bearer-token';.
error TypeError: bearerToken is not a function
cause Attempting to `require('koa-bearer-token')` as a default export in CommonJS after v2.0.0.
fix
Change the CommonJS require statement from const bearerToken = require('koa-bearer-token'); to const { bearerToken } = require('koa-bearer-token');.
error Error: You must pass secret option in order to sign/unsign cookie
cause When `cookie.signed` is set to `true`, the `secret` option is mandatory for cookie signing/unsigning.
fix
Provide a strong secret string via the cookie.secret option: bearerToken({ cookie: { signed: true, secret: 'YOUR_APP_SECRET' } }).
error Property 'token' does not exist on type 'Request'.
cause When using a custom `reqKey` (e.g., `reqKey: 'myToken'`) in TypeScript, the Koa `Request` interface does not automatically know about this new property.
fix
Perform module augmentation to extend the Koa Request interface: declare module 'koa' { interface Request { [myToken]?: string; } }.
breaking Version 2.0.0 introduced a breaking change by switching from default export to named export. Code using `require('koa-bearer-token')` or `import bearerToken from 'koa-bearer-token'` will fail.
fix Update CommonJS imports to `const { bearerToken } = require('koa-bearer-token');` and ESM imports to `import { bearerToken } from 'koa-bearer-token';`.
breaking Version 2.0.0 raised the minimum Node.js requirement to version 12. Applications running on older Node.js versions will encounter compatibility issues.
fix Ensure your Node.js environment is version 12 or newer. Update Node.js or use a compatible version of the library (e.g., 1.x.x for Node < 12).
gotcha When extracting tokens from cookies, failing to pass `{ signed: true }` makes your application vulnerable to cookie spoofing, as it will accept non-signed cookies.
fix Always use `{ signed: true }` for cookie parsing and provide a `secret` to ensure cookie integrity and prevent tampering: `bearerToken({ cookie: { signed: true, secret: 'YOUR_APP_SECRET' } })`.
gotcha If a token is found in more than one location (e.g., header and query), the middleware will abort the request with a 400 Bad Request status code, per RFC6750.
fix Ensure client applications send the bearer token in only one location (header, query, body, or cookie) to avoid 400 errors. This is intended RFC compliance, not a bug.
npm install koa-bearer-token
yarn add koa-bearer-token
pnpm add koa-bearer-token

Demonstrates setting up `koa-bearer-token` middleware with custom options, including cookie extraction and a custom request key, and then accessing the token within a Koa route handler.

import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import { bearerToken } from 'koa-bearer-token';

const app = new Koa();

app.use(bodyParser());
app.use(bearerToken({
  cookie: {
    signed: false, // Set to true if using signed cookies and provide a secret
    secret: process.env.COOKIE_SECRET ?? '', // Required if signed is true
    key: 'auth_token', // Custom cookie key
  },
  reqKey: 'myCustomToken',
}));

app.use((ctx) => {
  if (ctx.request.myCustomToken) {
    ctx.body = `Token found: ${ctx.request.myCustomToken}`;
  } else {
    ctx.status = 401;
    ctx.body = 'Authentication required';
  }
});

app.listen(3000, () => {
  console.log('Koa app listening on port 3000');
});