@ hapi / hawk的Hawk验证错误

时间:2019-07-16 11:04:47

标签: node.js hapijs

我正在尝试使用 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)'));
    });

1 个答案:

答案 0 :(得分:0)

我为此确切问题创建了PR :) https://github.com/hapijs/hawk/pull/259