npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

bearer-token-parser

v2.0.0

Published

This is a Bearer token authentication module that you can use with the Express framework.

Downloads

594

Readme

bearer-token-parser

This is a Bearer token authentication module that you can use with the Express framework.

Installation

npm i bearer-token-parser

API

See API.md for API reference.

Release Notes

All changes can be found here.

Quick Start

There is a sample app in "./example" to try token authentication.

  1. Move to the example directory.
    cd example/
  2. Install dependencies.
    npm install
  3. Start the app.
    npm start
  4. You can send an authentication request with curl.
    • Correct token
      # HTTP Status: 200 OK
      curl -I -H 'Authorization: Bearer mytoken123' http://localhost:3000/auth
    • Wrong token
      # HTTP Status: 401 Unauthorized  
      # WWW-Authenticate: Bearer realm="myapi", error="invalid_token", error_description="Token cannot be authenticated"
      curl -I -H 'Authorization: Bearer mytoken456' http://localhost:3000/auth
    • Missing Authorization header
      # HTTP Status: 401 Unauthorized  
      # WWW-Authenticate: Bearer realm="myapi", error="token_required"
      curl -I http://localhost:3000/auth
    • Authorization header but no Token
      # HTTP Status: 401 Unauthorized  
      # WWW-Authenticate: Bearer realm="myapi", error="invalid_token", error_description="Token format error"
      curl -I -H 'Authorization: Bearer ' http://localhost:3000/auth

Usage

  • An example of an Express framework.
    BearerParser can also be used with other frameworks.

    import express from 'express';
    import {BearerParser} from 'bearer-token-parser';
    
    const router = express.Router();
    router.post('/', async (req, res) => {
        // Get bearer token.
        const token = BearerParser.parseBearerTokenHeader(req);
    
        // Execute any process and response.
        res.json(true);
    });
    
    // mount the router on the app.
    app.use('/', router)
  • This is an example of validation of Bearer tokens.
    BearerValidator is a module dedicated to the Express framework.
    In case of verification error, the following response is automatically returned.

    |HTTP status|WWW-Authenticate response header|Descritpion| |-|-|-| |401 Unauthorized|Bearer realm="Your realm name", error="token_required"|If the token locale is Header and there is no Authorization header.or if the token localization is Body/Query and there is no token parameter.| |401 Unauthorized|Bearer realm="Your realm name", error="invalid_token", error_description="Token format error"|If the Bearer token is empty or incorrect as token68 format.| |401 Unauthorized|Bearer realm="Your realm name", error="invalid_token", error_description="Token cannot be authenticated"|If the token is unregistered or invalid and cannot be authenticated.This is the case when the return value of the optional tokenCheckCallback method is FALASE.| |400 Bad Request|Bearer realm="Your realm name", error="invalid_request"|In case of request body validation error.This is the case when the return value of the optional requestParameterCheck method is FALASE.|

    import express from 'express';
    import {BearerParser, BearerValidator} from 'bearer-token-parser';
    import {body, validationResult} from 'express-validator';
    
    const router = express.Router();
    router.post('/', [
        // Validation of input data by express-validator.
        body('email').isEmail(),
        body('name').isLength({min: 1, max: 20}),
    
        // Token authentication middleware initialization.
        BearerValidator.validation({
            // // Select the Token location as header/body/query.
            // tokenLocation: 'query',
    
            // // If the token location is query or body, specify the parameter name of the token.
            // tokenParameter: 'access_token',
    
            // Realm name to be included in response headers.
            realm: 'myapi',
            tokenCheckCallback: async (token) => {
                // Return `TRUE` if the token is correct.
                // If you return `FALSE`, a `401` error will be returned by the `BearerValidator.validation` middleware.
                return token === '<Your Bearer token>';
            },
            requestParameterCheck: (req) => {
                // Return `TRUE` if the input data is correct using `express-validator`.
                // If `FALSE` is returned, a `400` error is returned by the `BearerValidator.validation` middleware.
                const errors = validationResult(req);
                return errors.isEmpty();
            }
        }),
    ], async (req, res) => {
        // Get bearer token.
        const token = BearerParser.parseBearerTokenHeader(req);
    
        // Execute any process and response.
        res.json(true);
    });
    
    // mount the router on the app.
    app.use('/', router)

Testing

With npm do:

npm test

Author

Takuya Motoshima

License

MIT