Skip to content

Documentation on default auth strategy incorrect? #459

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions