MonkeyBonkey MonkeyBonkey - 4 years ago 127
Node.js Question

how to turn a hapi auth plugin to be optional

I'd like to use the hapi jwt token auth plugin https://github.com/ryanfitz/hapi-auth-jwt but make a route with optional authentication. How can I prevent the route from returning a 401 and instead continue executing with a null request.auth.credentials.

I'd like all the other routes that are using it to keep the same implementation of returning a 401 on non authenticated requests.

server.register(require('hapi-auth-jwt'), function (error) {

server.auth.strategy('token', 'jwt', {
key: privateKey,
validateFunc: validate
});

//make this one allow anonymous while also reading logged in credentials
server.route({
method: 'GET',
path: '/',
config: {
auth: 'token'
}
});

server.route({
method: 'GET',
path: '/mystuff',
config: {
auth: 'token'
}
});
});


server.start();

Answer Source

You can set it to optional in route configuration:

server.route({
    method: 'GET',
    path: '/',
    config: {
        auth: {
            strategy: 'token',
            mode: 'optional'
        }    
    }
});

Mode can be true, false, required, optional, or try. See the authentication tutorial for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download