cb不是hapi-auth-jwt2-Node.js中的函数

时间:2018-02-19 07:55:49

标签: javascript node.js jwt restful-authentication hapijs

我按照this教程在jwt authentication中实施hapijs v17.2

我根据教程做了一切,但是以下错误让我发疯,即使调试也没有做任何改变。

错误

Debug: internal, implementation, error
    TypeError: cb is not a function
    at Object.secretProvider [as key] (C:\Users\user\WebstormProjects\hapi-blog\node_modules\jwks-rsa\lib\integrations\hapi.js:30:14)
    at Object.authenticate (C:\Users\user\WebstormProjects\hapi-blog\node_modules\hapi-auth-jwt2\lib\index.js:123:87)
    at module.exports.internals.Manager.execute (C:\Users\user\WebstormProjects\hapi-blog\node_modules\hapi\lib\toolkit.js:35:106)
    at module.exports.internals.Auth._authenticate (C:\Users\user\WebstormProjects\hapi-blog\node_modules\hapi\lib\auth.js:242:58)
    at authenticate (C:\Users\user\WebstormProjects\hapi-blog\node_modules\hapi\lib\auth.js:217:21)
    at module.exports.internals.Request._lifecycle (C:\Users\user\WebstormProjects\hapi-blog\node_modules\hapi\lib\request.js:261:62)
    at <anonymous>

app.js

const hapi = require('hapi');
const mongoose = require('./db');
const hapi_auth_jwt = require('hapi-auth-jwt2');
const jwksa_rsa = require('jwks-rsa');
const dog_controller = require('./controllers/dog');

const server = new hapi.Server({
    host: 'localhost',
    port: 4200
});

const validate_user = (decoded, request, callback) => {
    console.log('Decoded', decoded);
    if (decoded && decoded.sub) {
        return callback(null, true, {});
    }

    return callback(null, true, {});
};

const register_routes = () => {
    server.route({
        method: 'GET',
        path: '/dogs',
        options: {
            handler: dog_controller.list,
            auth: false
        }
    });

    // Test
    server.route({
        method: 'POST',
        path: '/a',
        options: {
            handler: (req, h) => {
                return h.response({message: req.params.a});
            },
            auth: false
        }
    });

    server.route({
        method: 'GET',
        path: '/dogs/{id}',
        options: {
            handler: dog_controller.get
        }
    });

    server.route({
        method: 'POST',
        path: '/dogs',
        options: {
            handler: dog_controller.create
        }
    });

    server.route({
        method: 'PUT',
        path: '/dogs/{id}',
        handler: dog_controller.update
    });

    server.route({
        method: 'DELETE',
        path: '/dogs/{id}',
        handler: dog_controller.remove
    });
};

const init = async () => {
    await server.register(hapi_auth_jwt);

    server.auth.strategy('jwt', 'jwt', {
        key: jwksa_rsa.hapiJwt2Key({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            // YOUR-AUTH0-DOMAIN name e.g https://prosper.auth0.com
            jwksUri: 'https://mrvar.auth0.com/.well-known/jwks.json'
        }),
        verifyOptions: {
            audience: 'https://mrvar.auth0.com/api/v2/',
            issuer: 'https://mrvar.auth0.com',
            algorithm: ['RS256']
        },
        validate: validate_user
    });

    server.auth.default('jwt');

    // Register routes
    register_routes();

    // Start server
    await server.start();

    return server;
};

init().then(server => {
    console.log('Server running at: ', server.info.uri);
}).catch(err => {
    console.log(err);
});

当我向auth: false的路由发出请求时,处理程序正常工作,然后我得到了预期的结果,但是对没有auth的路由的请求返回以下json:

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "An internal server error occurred"
}

更多信息:

节点版本:8.9.4

npm版本:5.6.0

hapi版本:17.2.0

hapi-auth-jwt2:github:salzhrani / hapi-auth-jwt2#v-17

jwks-rsa:1.2.1

mongoose:5.0.6

nodemon:1.15.0

2 个答案:

答案 0 :(得分:4)

验证功能在hapi @ 17中更改为没有回调函数。根据您的示例,现在看起来应该是这样的:

const validate = async (decoded, request) => {
  if (decoded && decoded.sub) {
     return { isValid: true };
  }
  return { isValid: false };
};

返回对象的一部分还可以包含credentials,它代表经过身份验证的用户,您还可以将作用域作为凭据的一部分。

然后,如果您愿意,您可以像request

那样访问request.auth.credentials对象中的凭据

答案 1 :(得分:3)

两个库都支持hapi v.17

我也遇到了这个问题,但是令人惊讶的是,这两个库都支持hapi v.17,但是所有文档均基于旧版本或未使用此组合;)

使用方法

使用hapijs v.17只需更改几件事

验证您使用的是支持hapijs 17的库版本:

  • "jwks-rsa": "^1.3.0",
  • "hapi-auth-jwt2": "^8.0.0",

使用hapiJwt2KeyAsync代替hapiJwt2Key

有关此新异步方法的信息隐藏在node-jwks-rsa package documentation

validate函数现在具有新合同

请将现有的validate函数更改为以下类型:

async (decoded: any, request: hapi.Request): {isValid: boolean, credentials: {}} 

工作示例(具有已处理的传递范围)

const validateUser = async (decoded, request) => {
    if (decoded && decoded.sub) {
        return decoded.scope
            ? {
                isValid: true,
                credentials: {
                    scope: decoded.scope.split(' ')
                }
            }
            : { isValid: true };
    }

    return { isValid: false };
};

server.auth.strategy('jwt', 'jwt', {
    complete: true,
    key: jwksRsa.hapiJwt2KeyAsync({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: env.auth.jwksUri
    }),
    verifyOptions: {
        audience: '/admin',
        issuer: env.auth.issuer,
        algorithms: ['RS256']
    },
    validate: validateUser
});