Authorization Header middleware for Express and Sails.js
npm install authorization-header 
Authorization Header middleware for Express and Sails.js
Validates and extracts token value from Authorization Header of a given type, e.g. Bearer.
```
$ npm install authorization-header --save
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.
Default behavior
`javascript
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.
`javascript
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.
`javascript
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.);`
}));
Default behavior
`javascript`
// Will return 401 HTTP status code if any errors occurred.
// policies/authorizationHeader.js
module.exports = require('authorization-header')({ type: 'Digest' });
Default behavior
`javascript
// policies/authorizationHeader.js
module.exports = require('authorization-header')(function(err, req, res, next) {
if (!err) {
return next();
}
return res.unauthorized(err);
});
`
Possible thrown errors
| message | code |
| ---------------------------------------------------|:------------------------------------:|
| No Authorization header is present. | E_AUTHORIZATION_REQUIRED |Authorization:
| Formats should be . | E_AUTHORIZATION_INVALID_FORMAT |
| Authorization of type was expected. | E_AUTHORIZATION_INVALID_TYPE |E_AUTHORIZATION_INVALID_TOKEN
| Token provided is invalid. | |
Suppose E_AUTHORIZATION_INVALID_TYPE error was thrown
`javascript`
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'
}
*/
}
}));
```
$ npm test