Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 825
MonkeyBonkey Avatar asked Jan 30 '15 15:01

MonkeyBonkey


Video Answer


1 Answers

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.

like image 196
Gergo Erdosi Avatar answered Sep 30 '22 21:09

Gergo Erdosi