gpt4 book ai didi

javascript - hapi认证方案 : Set custom header

转载 作者:行者123 更新时间:2023-11-28 00:24:49 25 4
gpt4 key购买 nike

我正在 Hapi.js 中实现身份验证方案。

在我的 authenticate 函数中,我验证请求并希望设置自定义 header 。但由于我必须使用 reply.continue() 完成身份验证功能,因此我无法将任何 header 传递给响应。

如何将自定义 header 传递给客户端?

最少代码:

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')
};

最佳答案

解决方案是将 header 保存在插件数据中,并添加一个响应函数,该函数在身份验证后被调用,可用于向响应添加 header 。

更新后的代码:

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')
};

关于javascript - hapi认证方案 : Set custom header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com