Skip to content

Documentation on default auth strategy incorrect? #459

Closed

Description

@lauraseidler

Context

  • node version: 15.14.0
  • module version: 20.1.2

What are you trying to achieve or the steps to reproduce ?

I'm building an API where all routes are protected by a token based auth strategy. Now I'm trying to register a /health route, which should be exempt from the authentication for obvious reasons.

According to the documentation, defining the route before setting a default auth strategy should yield the desired behaviour:

Note that any routes added before server.auth.default() is called will not have the default applied to them.

However, with the following code (simplified to the relevant parts), I still get a 401 error when calling the /health endpoint:

const tokenScheme = function () {
    return {
        authenticate: async (request, h) => {
            const authorizationHeader = request.headers.authorization;

            const user = await getUser(authorizationHeader);

            if (user) {
                return h.unauthenticated(
                    Boom.unauthorized('Invalid token')'
                );
            }

            return h.authenticated({
                credentials: {
                    user,
                },
            });
        },
    };
};


server.route({
    method: 'GET',
    path: '/health',
    handler: () => {
        return 'up';
    },
});

server.auth.scheme('token', tokenScheme);
server.auth.strategy('token', 'token');
server.auth.default('token');

server.route({
    method: 'GET',
    path: '/user',
    handler: (request) => {
        return request.auth.credentials.user;
    },
});

Specifying

options: {
    auth: false,
}

on the /health route successfully disables authentication.

I'm unsure whether this is expected behaviour and the documentation is just incorrect, or whether this constitutes a bug. I'm happy to provide a PR for a fix either way, if you can clarify.

Activity

  1. devinivy commented on Apr 14, 2021

    @devinivy
    Member

    Hey, thanks for catching this! I believe the issue is just that the documentation is incorrect as of hapi v17. I am going to transfer this issue to the hapi.dev repo where this content lives 👍

  2. transferred this issue fromhapijs/hapion Apr 14, 2021
  3. lauraseidler commented on Apr 14, 2021

    @lauraseidler
    ContributorAuthor

    Great - I can prepare a PR tomorrow (at least for the English version - not sure how translations would be handled here).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions