【问题标题】:cb is not a function in hapi-auth-jwt2 - Node.jscb 不是 hapi-auth-jwt2 中的函数 - Node.js
【发布时间】:2018-07-29 10:06:32
【问题描述】:

我正在关注this 教程在hapijs v17.2 中实现jwt authentication

我按照教程做了所有的事情,但是下面的错误让我发疯了,即使调试也没有任何改变。

错误

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

猫鼬:5.0.6

nodemon:1.15.0

【问题讨论】:

  • 您是否仍然面临这个问题,您是否查看了我的最新答案?

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


【解决方案1】:

hapi@17 中的验证函数更改为没有回调函数。根据您的示例,它现在应该如下所示:

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

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

然后,如果您愿意,您可以将凭据作为request 对象的一部分访问,例如request.auth.credentials

【讨论】:

  • 虽然我使用了你的例子,但错误仍然存​​在。
  • 抱歉,我的回答是有效的,因为 validate 没有不是问题的回调。 jwksa_rsa 期待回调,但 hapi-auth-jwt2 不再向 key 函数发送回调。 jwksa_rsa hapi 代码尚未针对 hapi 17 更新
  • @HoomanL 您的问题可以通过此 PR 解决:github.com/auth0/node-jwks-rsa/pull/34
【解决方案2】:

两个库都支持 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
});

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 2021-10-07
    • 2018-05-30
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2018-06-30
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多