Reputation: 158
I'm trying to set up a simple authentication with Hapijs and its plugin hapi-auth-cookie, but even though the login seems to be successful (right now it's a mock login), when I try to access other endpoints of the API, I'm still getting unauthorized exception.
Here's my server:
server.register([inert, auth], function(err){
server.auth.strategy('base', 'cookie', {
password: 'supersecretpassword', // cookie secret
cookie: 'app-cookie', // Cookie name
ttl: 24 * 60 * 60 * 1000 // Set session to 1 day
});
server.auth.default({
strategy: 'base'
});
server.route(routes.endpoints);
//Start the server
server.start(function () {
console.log('Server running at:', server.info.uri);
});
});
And here are my login and logout functions:
exports.login = {
auth: false,
validate: {
payload: {
email: joi.string().email().required(),
password: joi.string().min(2).max(200).required()
}
},
handler: function(request, reply) {
if(request.payload.email === '[email protected]' && request.payload.password === 'password') {
request.auth.session.set({id: 123, email: '[email protected]'});
return reply('Login Successful');
} else {
return reply(boom.unauthorized('Bad email or password'));
}
}
};
exports.logout = {
auth: false,
handler: function(request, reply) {
request.auth.session.clear();
return reply('Logout Successful!');
}
};
When I hit the login endpoint, it replies with the "Login Successful" message but, as I said, can't access other endpoints that don't have "auth: false" within its config.
Any help will be deeply appreciated.
Upvotes: 0
Views: 1403
Reputation: 406
First check if the cookie is created on the browser. After this try to set the auth object like this:
auth: {mode:'required',strategy:'base'}
Other modes are: try, optional. Set optional if it doesn't matters if user is authenticated or not. Set required to the endpoints you want only to be accessed by authenticated users.
If you want to secure routes by user roles, you will need to set a scope attribute to the user object set on the session:
request.auth.session.set({id: 123, email: '[email protected]', scope:'admin'});
later on the auth object of the routes you set the scopes:
auth: {scope: ['admin']}
also set isSecure: false
when you create the strategy. This way the cookie is sent to the client.
Upvotes: 3