Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hapi-auth-cookie failing to load session strategy

There's not many examples out there for hapi and its auth-cookie plugin but here's what I have so far in an attempt to secure a route. Note, most of the examples I've seen are using an older version of hapi which doesn't seem to quite apply to this situation and im hoping im just missing something simple:

var Hapi = require('hapi');
var Mongoose = require('mongoose');

Mongoose.connect('mongodb://localhost/rfmproducetogo');

var server = new Hapi.Server(8080, "localhost");

server.pack.register([{
    plugin: require("lout")
}, {
    plugin: require('hapi-auth-cookie')
}, {
    plugin: require("./plugins/togo")
}, {
    plugin: require("./plugins/auth")
}], function(err) {
    if (err) throw err;
    server.auth.strategy('session', 'cookie', {
        password: 'shhasecret',
        cookie: 'wtfisthisfor',
        isSecure: false,
        redirectTo: false
    });
    server.start(function() {
        console.log("hapi server started @ " + server.info.uri);
    });
});

And in my togo plugin I have this route setup to use the session

exports.create = function(plugin) {
    plugin.route({
        method: 'POST',
        path: '/togo/add',
        handler: function(request, reply) {
            produce = new Produce();
            produce.label = request.payload.label;
            produce.price = request.payload.price;
            produce.uom = request.payload.uom;
            produce.category = request.payload.category;

            produce.save(function(err) {
                if (!err) {
                    reply(produce).created('/togo/' + produce._id);
                } else {
                    reply(err);
                }

            });
        },
        config: {
            auth: 'session'
        }
    });
};

The error im seeing is this:

/home/adam/Projects/bushhog/node_modules/hapi/node_modules/hoek/lib/index.js:421
    throw new Error(msgs.join(' ') || 'Unknown error');
          ^
Error: Unknown authentication strategy: session in path: /togo/add
    at Object.exports.assert (/home/adam/Projects/bushhog/node_modules/hapi/node_modules/hoek/lib/index.js:421:11)
    at /home/adam/Projects/bushhog/node_modules/hapi/lib/auth.js:123:14
    at Array.forEach (native)
    at internals.Auth._setupRoute (/home/adam/Projects/bushhog/node_modules/hapi/lib/auth.js:121:24)
    at new module.exports.internals.Route (/home/adam/Projects/bushhog/node_modules/hapi/lib/route.js:118:43)
    at /home/adam/Projects/bushhog/node_modules/hapi/lib/router.js:110:25
    at Array.forEach (native)
    at /home/adam/Projects/bushhog/node_modules/hapi/lib/router.js:107:17
    at Array.forEach (native)
    at internals.Router.add (/home/adam/Projects/bushhog/node_modules/hapi/lib/router.js:104:13)

Running node 0.10.28, hapijs 6.x, hapi-auth-cookie 1.02

like image 342
battlemidget Avatar asked Nov 11 '22 05:11

battlemidget


1 Answers

this issue occurs when you try to use an authentication strategy before it's actually available.

You're already following a good application setup by splitting the functionality into individual, small plugins with a given scope.


UPDATE: here's a dedicated tutorial for that problem, how to fix „unknown authentication strategy“


A good way to set up authentication and your plugins that rely on authentication is to create an extra "auth plugin" that adds your desired strategies and can be used as a dependency in your other plugins.

hapi auth plugin example

exports.register = function (server, options, next) {

  // declare/register dependencies
  server.register(require('hapi-auth-cookie'), err => {

    /**
     * Register authentication strategies to hapi server
     *
     * We’re using hapi-auth-cookie plugin to store user information on
     * client side to remember user data on every website visit
     *
     * For sure, we could and will add more authentication strategies.
     * What’s next: JWT (we highly welcome pull requests to add JWT functionality!)
     */
    server.auth.strategy('session', 'cookie', {
      password: 'ThisIsASecretPasswordThisIsASecretPassword',
      cookie: 'hapi-rethink-dash',
      redirectTo: '/login',
      isSecure: false
    });

    server.log('info', 'Plugin registered: cookie authentication with strategy »session«')

    next()

  })

}

exports.register.attributes = {
  name: 'authentication',
  version: '1.0.0'
}

In your /plugins/togo you set the authentication plugin as a dependency (with server.dependency([array-of-deps])) which means hapi registers the auth plugin first and the depending ones afterwards.

You register your plugins like this:

server.register([{
    plugin: require('./plugins/authentication')
}, {
    plugin: require("./plugins/togo")
}], function(err) { 
  // handle callback
})

Check hapi-rethinkdb-dash for a detailed example.

Hope that helps!

like image 81
Marcus Poehls Avatar answered Dec 01 '22 06:12

Marcus Poehls