polka-bearer-token
v1.0.0
Published
Bearer token middleware for Polka.
Maintainers
Readme
polka-bearer-token
Bearer token middleware for Polka. Ported from express-bearer-token.
Supports Polka@next.
Install
npm install polka-bearer-tokenyarn add polka-bearer-tokenpnpm add polka-bearer-tokenUsage
import polka from "polka";
import bearerToken from "polka-bearer-token";
const app = polka()
.use(bearerToken())
.use((req, res, next) => {
console.log(req.token);
next();
})
.listen(8000);Per RFC6750, this middleware attempts to read a bearer token from a request at these locations:
- The key
access_tokenin the request body. - The key
access_tokenin the request params. - The value from the header
Authorization: Bearer <token>. - (Optionally) The value from cookies header with key
access_token.
If a token is found, it will be stored on req.token. If one was provided in more than one location, the request will be aborted with code 400. (See continueOnMultiple for passing the error through next() instead.)
API
bearerToken(options?): Polka.Middleware
Returns a configured Polka middleware.
options
Type: object
For APIs which are not compliant with RFC6750, the key for the token in each location is customizable.
bodyKey
Type: string
Default: "access_token"
The key that will be used to find the token in the request body. The body must have already been parsed by an earlier middleware.
queryKey
Type: string
Default: "access_token"
The key that will be used to find the token in the request params.
headerKey
Type: string
Default: "Bearer"
The value that will be used to find the token in the request header. Case-insensitive.
cookie
Type: boolean | object
Default: false
Set to enable cookie parsing. Optionally uses the provided secret key(s) to decode an Express-style signed cookie (s:<value>.<signature>).
Setting this to true uses the default { key: "access_token" }.
[!IMPORTANT] Using signed cookies is strongly recommended.
key
Type: string
Default: "access_token"
The key that will be used to find the token in the request cookies.
secret
Type: string | string[]
The secret key used to sign the cookie. If an array is provided, each secret will attempt to decode the signed cookie in order.
continueOnMultiple
Type: boolean
Default: false
Whether or not the middleware should call next() or end the response if multiple tokens are provided.
If true, next() is called with an error of the shape:
{
"message": "Bearer token provided multiple times.",
"status": 400
}This can then be handled in Polka's options.onError handler.
Related
- express-bearer-token - Bearer token middleware for express.
- koa-bearer-token - Bearer token parser middleware for koa.
