johnbrett / hapi-auth-bearer-token

Simple Bearer authentication scheme plugin for hapi, accepts token by Header, Cookie or Query parameter.
MIT License
218 stars 46 forks source link

hapi auth bearer token

Build Status

[Release Notes] @hapi/hapi, joi, and @hapi/boom are all now peer dependencies to allow maximum flexibility. A reference to joi is now required as opposed to the older @hapi/joi.

For hapi 17.x and above used in combination with the new joi v17.x package. Requires Node 12 or greater.

Note: For hapi v17 and above implementations using @hapi/joi, it is recommended to use Version 6.x.x of this module.

Note: For hapi versions below v17, you must use versions v5.x.x of this module.

Lead Maintainer: John Brett

Bearer authentication requires validating a token passed in by bearer authorization header or query parameter.

This module creates a 'bearer-access-token' scheme takes the following options:

const Hapi = require('hapi');
const AuthBearer = require('hapi-auth-bearer-token');

const server = Hapi.server({ port: 8080 });

const start = async () => {

    await server.register(AuthBearer)

    server.auth.strategy('simple', 'bearer-access-token', {
        allowQueryToken: true,              // optional, false by default
        validate: async (request, token, h) => {

            // here is where you validate your token
            // comparing with token from your database for example
            const isValid = token === '1234';

            const credentials = { token };
            const artifacts = { test: 'info' };

            return { isValid, credentials, artifacts };
        }
    });

    server.auth.default('simple');

    server.route({
        method: 'GET',
        path: '/',
        handler: async function (request, h) {

            return { info: 'success!' };
        }
    });

    await server.start();

    return server;
}

start()
    .then((server) => console.log(`Server listening on ${server.info.uri}`))
    .catch(err => {

        console.error(err);
        process.exit(1);
    })

/*
 * To test this example, from your terminal try:
 *  curl localhost:8080
 *     response: {"statusCode":401,"error":"Unauthorized","message":"Missing authentication"}
 *  curl localhost:8080?access_token=abc
 *     response: {"statusCode":401,"error":"Unauthorized","message":"Bad token","attributes":{"error":"Bad token"}}
 *  curl localhost:8080?access_token=1234
 *     response: {"info":"success!"}
 */

License MIT @ John Brett and other contributors 2018