Search code examples
node.jsauthenticationhapi

hapi-auth-bearer-token only works for an access_token in query string not as a header


How to I get hapi-auth-bearer-token to work using the access_token as an http headers instead of passing it in the query string? The documentation is pretty clear that this should work, but it does not as you can see from my screenshots below.

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);
    })

Query string access_token works:

Query string works:

Header access_token does not:

enter image description here


Solution

  • hapi-auth-bearer-token requires a bearer token which means the value needs to be Bearer 1234 not just 1234. In my case I had to use it without the word Bearer so I dug into the plugin source code and rolled my own implementation.