Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hapi multiple auth strategy not working as expected #3444

Closed
joaom182 opened this Issue Feb 26, 2017 · 6 comments

Comments

Projects
None yet
4 participants
@joaom182
Copy link

commented Feb 26, 2017

Explanation

I'm trying to implement a route with multiple auth strategy, and not working as expected, and i think this is a bug.

This is how i register strategies

server.auth.strategy('token-adm', 'jwt', {
    key: new Buffer(process.env.AUTH0_SQUID_ADM_CLIENT_SECRET, 'base64'),
    verifyOptions: {
        algorithms: ['HS256'],
        audience: process.env.AUTH0_SQUID_ADM_CLIENT_ID,
    }
});

server.auth.strategy('token-client', 'jwt', {
    key: new Buffer(process.env.AUTH0_SQUID_CLIENT_SECRET, 'base64'),
    verifyOptions: {
        algorithms: ['HS256'],
        audience: process.env.AUTH0_SQUID_CLIENT_ID,
    }
});

And this is how i configured the route

server.route({
    path: '/midias',
    method: 'GET',
    handler: midiasHandler,
    config: {
        auth: {
            strategies: ['token-client', 'token-adm'],
        },
    },
});

The results

When i request the endpoint /midias with the Authorization header with a VALID token-client, the server returns 200 OK as expected. BUT when i request the same endpoint with a VALID token-adm, the server returns 401 Unauthorized as not expected.

So.. i realized what the auth strategy is validating only the first strategy on array... because when i change the order.. putting the token-adm to first on array, the request with token-adm returns 200 OK as expected, and token-client returns 401 Unauthorized as not expected.

To confirm if the token-client and token-adm is valid, i configured the route with unique strategy at a time, and request the endpoint at a time, and the requests returns 200 OK as expected when token is valid, and 401 Unauthorized as expected when token is invalid.

My expectation

My expectation is when i request a endpoint with multiple strategy, the mechanism try to validate the auth at least with one strategy, and not only the first on array.

Context

  • node version: v6.3.1
  • hapi version: v15.1.1
  • os: macOS Sierra 10.12.2

@joaom182 joaom182 changed the title Hapi multiple auth strategy not working Hapi multiple auth strategy not working as expected Feb 26, 2017

@hueniverse

This comment has been minimized.

Copy link
Member

commented Feb 27, 2017

You can't have two strategies using the same header scheme. You have a single incoming authorization credential that can match one of two sources (client, admin). You need to construct one strategy that checks one, then the other. hapi has no way of knowing why the first one failed (e.g. it was the wrong kind of credentials).

@hueniverse hueniverse closed this Feb 27, 2017

@hueniverse hueniverse self-assigned this Feb 27, 2017

@hueniverse hueniverse added the question label Feb 27, 2017

@timotgl

This comment has been minimized.

Copy link

commented May 10, 2017

@hueniverse How would one go about doing this? Does this require a custom scheme as well? My issue is that I'd like to use two strategies on a route that both look at the Authorization header with a bearer token (hapi-auth-jwt and hapi-auth-bearer-token) (I had the same expectation as @joaom182).

@hueniverse

This comment has been minimized.

Copy link
Member

commented May 25, 2017

You would need to write a new scheme that uses the auth test() api to try each scheme "manually".

@timotgl

This comment has been minimized.

Copy link

commented May 25, 2017

For anyone who ends up here, this is a draft for how the use case of an ambiguous bearer token can be implemented:

/* combinedBearerTokenAuthScheme.js */

const Boom = require('boom');

const headerPattern = /^Bearer (.+)/;

const testAuth = (request, strategy) => new Promise((resolve, reject) => {
  request.server.auth.test(strategy, request, (error, credentials) => {
    if (error === null) {
      resolve(credentials);
    } else {
      reject(error);
    }
  });
});

/*
 * Derive auth strategy to be used from the bearer token.
 */
const strategyForToken = (token) => {
  let strategy = false;
  if (conditionToDetectFirstStrategy) {
    strategy = 'firstStrategyHere';
  } else if (conditionToDetectSecondStrategy) {
    strategy = 'secondStrategyHere';
  }

  return strategy;
};

/*
 * Extract bearer token from request and identify which auth strategy it is meant for.
 */
const authenticate = async (request, reply) => {
  // Reject missing or invalid header.
  const header = request.headers.authorization;
  if (!header || !headerPattern.test(header)) {
    return reply(Boom.badRequest('Missing or invalid authorization header'), {}, {});
  }

  const token = header.match(headerPattern)[1];
  const strategy = strategyForToken(token);

  if (!strategy) {
    return reply(Boom.badRequest('Unable to determine auth strategy'), {}, {});
  }

  try {
    const credentials = await testAuth(request, strategy);

    // Remember which strategy was successfully tested.
    const artifacts = { actualStrategy: strategy };

    return reply.continue({ credentials, artifacts });
  } catch (error) {
    return reply(error, {}, {});
  }
};

module.exports = {
  scheme: () => ({ authenticate })
};
@joaom182

This comment has been minimized.

Copy link
Author

commented Aug 2, 2018

Simple great solution for this behavior -> https://github.com/cjihrig/nuisance

@CelsoEspinoza

This comment has been minimized.

Copy link

commented Apr 15, 2019

Simple great solution for this behavior -> https://github.com/cjihrig/nuisance

How did you implemented?
It gives me this error: ZOMG A FATAL ERROR { AssertionError [ERR_ASSERTION]: Authentication strategy storeSimple uses unknown scheme: nuisance

'use strict';

function register(server) {
	server.auth.strategy('storeSimple', 'nuisance', {
		strategies: ['store', 'simple'],
	});
}

const plugin = {
	name: 'store-simplee',
	register,
	version: '1.0.0',
};

module.exports = plugin;

Then, I use it in my route service and gave that error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.