authorization-header

0.2.0 • Public • Published

node-authorization-header

npm version Build Status

Authorization Header middleware for Express and Sails.js

Validates and extracts token value from Authorization Header of a given type, e.g. Bearer.

Install

$ npm install authorization-header --save

Overview

authorizationHeader(options, [callback])

options

  • type The type of Authorization, e.g. Bearer, Basic, Digest, etc.
  • attachTo Where the token value extracted will be attach to, defaults to token.
  • compareTo This options allows user to pass a value to compare against the extracted token.

Usage in Express

Default behavior

const authorizationHeader = require('authorization-header');
 
app.get('/', authorizationHeader(), function(req, res) {
  // toke value extracted can be found at `req.token`
});

Usage of type and attachTo options.

const authorizationHeader = require('authorization-header');
 
app.use(authorizationHeader({
  type: 'Basic',
  attachTo: 'apiKey'
});
 
app.get('/', function(req, res) {
  res.send(req.apiKey);
});

Usage of compareTo option.

app.get('/', authorizationHeader({
  compareTo: TOKEN_VALUE
}, function(err, req, res, next) {
  if (err) {
    return res.status(401).send(err);
  }
 
  return res.send(`Your token is valid.`);
}));

Usage in Sails.js

Default behavior

// Will return 401 HTTP status code if any errors occurred.
// policies/authorizationHeader.js
module.exports = require('authorization-header')({ type: 'Digest' });

Default behavior

// policies/authorizationHeader.js
module.exports = require('authorization-header')(function(err, req, res, next) {
  if (!err) {
    return next();
  }
 
  return res.unauthorized(err);
});

Error handling

Possible thrown errors

AuthorizationHeaderError

message code
No Authorization header is present. E_AUTHORIZATION_REQUIRED
Formats should be Authorization: <type> <token>. E_AUTHORIZATION_INVALID_FORMAT
Authorization of type <type> was expected. E_AUTHORIZATION_INVALID_TYPE
Token provided is invalid. E_AUTHORIZATION_INVALID_TOKEN

Suppose E_AUTHORIZATION_INVALID_TYPE error was thrown

app.use(authorizationHeader(function(err, req, res, next) {
  if (err) {
    console.log(err.toJSON());
    /*
      {
        status: 401,
        message: 'Authorization of type Bearer was expected',
        code: 'E_AUTHORIZATION_INVALID_TYPE'
      }
    */
  }
}));

Test

$ npm test

Package Sidebar

Install

npm i authorization-header

Weekly Downloads

15

Version

0.2.0

License

MIT

Last publish

Collaborators

  • joshua.marquez