Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

express-bearer-token

tkellen161.5k3.0.0TypeScript support: included

Bearer token middleware for express.

bearer token, bearer token middleware, express token, authorization bearer

readme

express-bearer-token Build Status

Bearer token middleware for express.

NPM

What?

Per RFC6750 this module will attempt to extract a bearer token from a request from these locations:

  • The key access_token in the request body.
  • The key access_token in the request params.
  • The value from the header Authorization: Bearer <token>.
  • (Optional) Get a token from cookies header with key access_token.

If a token is found, it will be stored on req.token. If one has been provided in more than one location, this will abort the request immediately by sending code 400 (per RFC6750).

const express = require('express');
const bearerToken = require('express-bearer-token');
const app = express();

app.use(bearerToken());
app.use(function (req, res) {
  res.send('Token '+req.token);
});
app.listen(8000);

For APIs which are not compliant with RFC6750, the key for the token in each location is customizable, as is the key the token is bound to on the request (default configuration shown):

app.use(bearerToken({
  bodyKey: 'access_token',
  queryKey: 'access_token',
  headerKey: 'Bearer',
  reqKey: 'token',
  cookie: false, // by default is disabled
}));

Get token from cookie key (it can be signed or not)

Warning: by NOT passing {signed: true} you are accepting a non signed cookie and an attacker might spoof the cookies. so keep in mind to use signed cookies

app.use(bearerToken({
  cookie: {
    signed: true, // if passed true you must pass secret otherwise will throw error
    secret: 'YOUR_APP_SECRET',
    key: 'access_token' // default value
  }
}));

As of version 2.2.0 we've added initial support for TypeScript.

changelog

v3.0.0: date: 2024-11-11 changes:

- bump dependency on cookie module to ^1.0.1 to address https://github.com/advisories/GHSA-pxg6-pf52-xh8x (a bc break, so new major version)
- bump mocha dependency to silence other warnings (these were not a concern in production)
- update `var` to `const` in tests

v2.4.0: date: 2019-04-06 changes:

- update dependenices
- swap from yarn to npm package manager
- update syntax to es6

v2.3.0: date: 2019-04-06 changes:

- search for bearer in signed/unsigned cookies header
- raising the minimum supported nodejs version

v2.2.0: date: 2018-08-09 changes:

- added typescript support

v2.1.1: date: 2017-12-06 changes:

- Update express api - `res.send(code)` to `res.status(code).send()`

v2.1.0: date: 2015-01-21 changes:

- Support custom req key.

v2.0.0: date: 2014-09-01 changes:

- Support custom access_token keys.

v1.0.1: date: 2014-09-01 changes:

- Initial release.