Socket
Socket
Sign inDemoInstall

bearer-token-parser

Package Overview
Dependencies
244
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    bearer-token-parser

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


Version published
Weekly downloads
81
decreased by-65.97%
Maintainers
1
Install size
2.59 MB
Created
Weekly downloads
 

Changelog

Source

[2.0.0] - 2024/3/19

Added

  • The token parser class (BearerParser class) now supports methods to retrieve tokens from Query or Body. See the API reference for more details.

    |Method|Description| |--|--| |BearerParser.parseBearerToken()|Alias for BearerParser.parseBearerTokenHeader.| |BearerParser.parseBearerTokenHeader()|New. Get the bearer token from the Authorization request header.| |BearerParser.parseBearerTokenQuery()|New. Get a bearer token from the query parameter.| |BearerParser.parseBearerTokenBody()|New. Get a bearer token from the body parameter.|

  • Token authentication middleware (BearerValidator class) now supports Query or Body token validation.
    To validate a Query or Body token, specify query or body in the tokenLocation option and the parameter name of the token in the tokenParameter option.
    See the API reference for more details.

    // 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>';
        },
    }),
    

Changed

  • TypeScript was updated from version 3 to 5.
  • The parameter type of BearerParser.parseBearerToken() has changed.
    The parameter type used to be {authorization: string}, but now it is {headers: {authorization: string}}.

Readme

Source

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 statusWWW-Authenticate response headerDescritpion
    401 UnauthorizedBearer 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 UnauthorizedBearer realm="Your realm name", error="invalid_token", error_description="Token format error"If the Bearer token is empty or incorrect as token68 format.
    401 UnauthorizedBearer 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 RequestBearer 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

Keywords

FAQs

Last updated on 19 Mar 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc