auth-bearer-parser
This is a parsing middleware for Bearer tokens that can be used with the Express framework.
Parse the Authorization
header and assign the Bearer token to req.token
.
Installation
npm
$ npm install bearer-token-parser
yarn
$ yarn add bearer-token-parser
Usage
TypeScript
import express, { Request, Response } from 'express';
import authBearerParser from 'auth-bearer-parser';
const app = express();
app.use(authBearerParser());
app.get('/', (req: Request, res: Response) => {
console.log(req.token);
...
});
...
JavaScript
ES Module
import express from 'express';
import authBearerParser from 'auth-bearer-parser';
const app = express();
app.use(authBearerParser());
app.get('/', (req, res) => {
console.log(req.token);
...
});
...
CommonJS
Note that you should be require('...').default
.
const express = require('express');
const authBearerParser = require('auth-bearer-parser').default;
const app = express();
app.use(authBearerParser());
app.get('/', (req, res) => {
console.log(req.token);
...
});
...
API
authBearerParser(options)
-> void
options
Optional
Type: object
isThrowError
Optional
Type: boolean
Default: false
If true, throw error when bearer token is invalid.
The error objects thrown are as follows.
status | message |
---|
401 | authorization header missing |
400 | invalid token type: ${auth-scheme} ※auth-scheme is Basic or Digest and so on |
401 | token missing |
To catch errors thrown and continue processing, the default error handling of express can be changed to any error by extending it. An example is shown below.
import express from 'express';
import authBearerParser from 'auth-bearer-parser';
const app = express();
app.use(authBearerParser({ isThrowError: true }));
app.use((err, req, res, next) => {
res.status(err.status | 500).json({ message: err.message });
});
License
MIT licensed