Reputation: 1687
I’m implementing an authentication scheme in Hapi.js.
In my authenticate
function I verify the request and want to set a custom header. But as I have to finish the authenticate function with a reply.continue()
, I cannot pass any headers to the response.
How can I pass my custom header to the client?
Minimal code:
var Boom = require('boom'),
Hoek = require('hoek'),
request = require('request');
exports.register = function(plugin, config, next) {
plugin.auth.scheme('myScheme', function(server, options) {
Hoek.assert(options, 'Missing auth strategy options');
return {
authenticate: function(req, reply) {
request(
'http://localhost/somewhere',
function(error, response, body) {
if (error) {
return reply(null, null, Boom.unauthorized(null, 'myScheme'));
}
options.validateFunc(
body,
function(validateError, isValid, credentials) {
if (validateError || !isValid) {
return reply(
Boom.unauthorized('Invalid cookie'),
null,
{credentials: credentials}
);
}
// I want to add a custom header here
//.header('my-header', 'my-header-content')
return reply
.continue({
credentials: credentials || body
}));
}
);
}
);
}
};
});
next();
};
exports.register.attributes = {
pkg: require('../package.json')
};
Upvotes: 1
Views: 1903
Reputation: 1687
The solution was to save the header in the plugin data and add a response
function, that gets called after the authentication and can be used to add headers to the response.
The updated code:
var Boom = require('boom'),
Hoek = require('hoek'),
request = require('request');
exports.register = function(plugin, config, next) {
plugin.auth.scheme('myScheme', function(server, options) {
Hoek.assert(options, 'Missing auth strategy options');
return {
// add headers to the response.
response: function(request, reply) {
var pluginData = request.plugins['myScheme'];
if (pluginData && pluginData['my-header']) {
request.response.header('my-header', pluginData['my-header']);
}
reply.continue();
},
authenticate: function(req, reply) {
request(
'http://localhost/somewhere',
function(error, response, body) {
if (error) {
return reply(null, null, Boom.unauthorized(null, 'myScheme'));
}
options.validateFunc(
body,
function(validateError, isValid, credentials) {
if (validateError || !isValid) {
return reply(
Boom.unauthorized('Invalid cookie'),
null,
{credentials: credentials}
);
}
// save header in the plugin data
request.plugins['myScheme'] = {
'my-header': 'my-header-content'
};
return reply
.continue({
credentials: credentials || body
}));
}
);
}
);
}
};
});
next();
};
exports.register.attributes = {
pkg: require('../package.json')
};
Upvotes: 1