Hapijs中缺少状态码为401的身份验证?

时间:2017-03-22 07:49:03

标签: node.js hapijs

我是hapijs的新手,我正在使用hapi-auth-basic进行身份验证的演示应用。 但我的代码,   (server.auth.strategy('simple', 'basic', { validateFunc: validate});validate方法未调用,结果总是未经授权,如下所示:

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "Missing authentication"
}

我想授权,任何人都可以建议我做什么以及我做错了什么?

'use strict';

const Bcrypt = require('bcrypt');
const Hapi = require('hapi');
const Basic = require('hapi-auth-basic');

const server = new Hapi.Server();
server.connection({ port: 3000 });

const users = {
    john: {
        username: 'john',
        password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',   // 'secret'
        name: 'John Doe',
        id: '2133d32a'
    }
};

const validate = function (request, username, password, callback) {
    const user = 'john';
    console.log("1");
    if (!user) {
        return callback(null, false);
    }

    Bcrypt.compare(12345, 12345, (err, isValid) => {
        console.log("2");
        callback(err, isValid, { id: user.id, name: user.name });
    });
};

server.register(Basic, (err) => {
console.log("3");
    if (err) {
        throw err;
    }

    server.auth.strategy('simple', 'basic', { validateFunc: validate});
    server.route({
        method: 'GET',
        path: '/',
        config: {
            auth: 'simple',
            handler: function (request, reply) {
                console.log("4");
                reply('hello, ' + request.auth.credentials.name);
            }
        }
    });

    server.start((err) => {

        if (err) {
            throw err;
        }

        console.log('server running at: ' + server.info.uri);
    });
});

3 个答案:

答案 0 :(得分:0)

在验证函数中,Bcrypt必须响应错误或isValid为false,您必须测试这些返回条件,而不是盲目地从函数返回结果。也总是在回调前使用return来显示控制流是否离开功能。使用像hapi的风格指南之类的东西来帮助早点发现错误。

答案 1 :(得分:0)

您应该在“授权”标头中发送身份验证数据。下面是由邮递员生成的curl示例。

curl -X GET \
  http://localhost:8080 \
  -H 'Authorization: Basic am9objokMmEkMTAkaXFKU0hELkJHcjBFMkl4UXdZZ0ptZVAzTnZoUHJYQWVMU2FHQ2o2SVIvWFU1UXRqVnU1VG0=' \
  -H 'cache-control: no-cache'

答案 2 :(得分:-1)

您应该创建一个方案,然后注册这样的策略:

;Copy array somewhere else, while reversing the order of elements
;
;Input
; ecx    Number of elements in array
; esi    Address of source array
; edi    Address of destination array

reverseArray:
    mov ebx,esp           ;ebx = stack top
    lea esp,[edi+ecx*4]   ;esp = address of byte after array
    cld
.next:
    lodsd                 ;eax = next element in source array
    push eax              ;Store it in destination array
    loop .next            ;Do all elements

    mov esp,ebx           ;Restore stack
    ret