hapi Bearer Token Authentication Scheme
The plugin requires validating a token passed in by the bearer authorization header. The validation function is something you have to provide to the plugin.
var validateFunction = function (token, callback) {
// Use a real strategy here to check if the token is valid
if (token === 'abc456789') {
callback(null, true, userCredentials);
} else {
callback(null, false, userCredentials);
}
};
server.register(require('hapi-auth-bearer-simple'), function (err) {
if (err) throw err;
server.auth.strategy('bearer', 'bearerAuth', {
validateFunction: validateFunction
});
// Add a standard route here as example
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply({ success: true });
},
config: {
auth: {
strategy: 'bearer',
scope: 'user' // or [ 'user', 'admin' ]
}
}
});
server.start(function () {
server.log([],'Server started at: ' + server.info.uri);
});
});
validateFunc
- (required) a token lookup and validation function with the signaturefunction (token, [request], callback)
token
- the auth token received from the client.request
- Optional request object. See below.callback
- a callback function with the signaturefunction (err, isValid, credentials)
where:err
- any error.isValid
-true
if both the username was found and the password matched, otherwisefalse
.credentials
- an object passed back to the plugin and which will become available in therequest
object asrequest.auth.credentials
. Normally credentials are only included whenisValid
istrue
. This object can be only the token as in the example but is preferably all the info you need from the authenticated user
exposeRequest
- (optional / advanced) If set totrue
thevalidateFunction
's signature will befunction (token, request, callback)
. This can be usefull if you have plugins that expose certain functions/object to therequest
object and you want to use them in yourvalidateFunction
. Be aware that modifying the object is not recommended because this is the same object that you will use in the whole lifecycle. Also exposing functions/object to theresuest
object during the validation is not recommended. Follow theHapi
standards whenever you can!
- 100% code coverage!
- You can chain strategies see http://hapijs.com/api#serverauthschemename-scheme.
- If you have any problems and/or questions make a new issue.
- If you want to contribute feel free to fork and add a pull request or again make an issue.