我正在尝试使用 Hawk 方案和 Hapi 验证基本示例,但 hawk 插件失败,因为它尝试访问不存在的 payload
属性:
错误:
Server started listening on http://localhost:3000
Debug: internal, implementation, error
TypeError: Cannot read property 'payload' of undefined
at Object.authenticate (D:\TEST\node\sample3\node_modules\@hapi\hawk\lib\plugin.js:45:45)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
相关Hawk插件code错误产生的位置:
...
if (request.route.settings.auth.payload) {
request.events.once('peek', (chunk) => {
...
服务器代码:
const Hapi = require('@hapi/hapi');
const Hawk = require('@hapi/hawk');
const credentials = {
John: {
key: 'secret',
algorithm: 'sha256'
}
};
const getCredentialsFunc = function (id) {
return credentials[id];
};
const start = async () => {
const server = Hapi.server({ port: 3000, host: 'localhost' });
await server.register(Hawk);
server.auth.strategy('default', 'hawk', { getCredentialsFunc });
server.auth.default('default');
server.route({
method: 'GET',
path: '/',
handler: function (request, h) {
return 'Welcome';
}
});
await server.start();
console.log('Server started listening on %s', server.info.uri);
};
start();
客户端代码:
const Request = require('request');
const Hawk = require('@hapi/hawk');
const credentials = {
id: 'John',
key: 'secret',
algorithm: 'sha256'
};
const requestOptions = {
uri: 'http://localhost:3000/',
method: 'GET',
headers: {}
};
const { header } = Hawk.client.header(requestOptions.uri, requestOptions.method, { credentials: credentials, ext: 'some-app-data' });
requestOptions.headers.Authorization = header;
Request(requestOptions, function (error, response, body) {
const isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
console.log(`${response.statusCode}: ${body}` + (isValid ? ' (valid)' : ' (invalid)'));
});
我是一名优秀的程序员,十分优秀!