Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cb is not a function in hapi.js #3742

Closed
ModernHooman opened this issue Feb 19, 2018 · 10 comments
Closed

cb is not a function in hapi.js #3742

ModernHooman opened this issue Feb 19, 2018 · 10 comments
Assignees
Labels
follow instructions The issue failed to follow instructions, try again

Comments

@ModernHooman
Copy link

ModernHooman commented Feb 19, 2018

I'm following this tutorial to implement jwt authentication in hapijs v17.2.

I did everything according to the tutorial, but the following error is driving me crazy, even debugging didn't make any change.

Error

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);
});

When I make a request to routes with auth: false, the handler works properly then I get the expected result, but requests to routes without auth return the following json :

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

More info:

node version: 8.9.4

npm version: 5.6.0

hapi version: 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

@Marsup
Copy link
Contributor

Marsup commented Feb 19, 2018

This is clearly not a problem with hapi itself but with the modules you're using. Have you read the issue template before posting ?
Also, no idea which tutorial you're referring to, I'm afraid I don't know this fork of hapi-auth-jwt2 but it appears not to be working.

@Marsup Marsup closed this as completed Feb 19, 2018
@Marsup Marsup self-assigned this Feb 19, 2018
@kshoultz
Copy link

kshoultz commented Feb 21, 2018

I am running into the same problem. I just found this thread and wanted to clarify for him. This is the tutorial he's referring to:
https://auth0.com/blog/developing-restful-apis-with-hapijs/

I know hapi.js has authentication built in. The approach mentioned in this article is brand specific to auth0. I'm sure there is a more general way. I will be looking for it in the documentation and starting there.

@cjihrig
Copy link
Contributor

cjihrig commented Feb 21, 2018

The problem is written in the tutorial:

The hapi-auth-jwt2 module is a library that validates a JSON Web Token in your headers, query or cookies for your application. At the time of this writing, a PR has been submitted to support Hapi v17. We can only make use of the repo by installing it via the GitHub repo.

The module doesn't work with hapi 17. You can try hapi 16 I guess.

EDIT: The PR in question is dwyl/hapi-auth-jwt2#249
EDIT: Sorry, I just re-read the conversation and see that you're using a v17 branch. It still doesn't appear to be a problem with hapi itself though.

@clarkie
Copy link

clarkie commented Feb 23, 2018

I'm having the same issue I have identified it down to this function here https://github.com/auth0/node-jwks-rsa/blob/master/src/integrations/hapi.js#L24 not working with the v17 branch. I'll see what I can do and try and submit a PR somewhere that makes sense.

@clarkie
Copy link

clarkie commented Feb 24, 2018

auth0/node-jwks-rsa#34

@johnmadden86
Copy link

johnmadden86 commented Feb 28, 2018

I'm only a novice but I think the problem is that the validate_user method uses old style callbacks instead of the new hapi response toolkit.
Try something like this:

const validate_user = (decoded, request, h) => {
  console.log('Decoded', decoded);
     try {
        return h.authenticated({ credentials: decoded.sub });
      } catch (err) {
        return h.unauthenticated(err);
    }
};

``

@jamalsoueidan
Copy link

I still have same issues, how did you solve this?

Debug: internal, implementation, error
    TypeError: cb is not a function
    at Object.secretProvider [as key] (C:\Users\Jamal\reactjs\shopify-express-application\node_modules\jwks-rsa\lib\integrations\hapi.js:47:14)

I tried to follow this example:
https://stackoverflow.com/questions/48861644/cb-is-not-a-function-in-hapi-auth-jwt2-node-js

Not working either, I'm using these versions.

"dependencies": {
    "hapi": "^17.0.0",
    "hapi-auth-jwt2": "^8.0.0",
    "jsonwebtoken": "^8.3.0",
    "jwks-rsa": "^1.3.0"
  }

I even created a issue on hapi-auth-jwt2.

dwyl/hapi-auth-jwt2#285

@aronsuarez
Copy link

@jamalsoueidan change this line

jwksRsa.hapiJwt2Key

to this

jwksRsa.hapiJwt2KeyAsync

@ghuser
Copy link

ghuser commented Oct 30, 2018

@aronsuarez I get

jwksRsa.hapiJwt2KeyAsync is not a function

@aronsuarez
Copy link

The code below is tested and running with the following packages:

"hapi-auth-jwt2": "^8.1.0",
"hapi-openapi": "^1.0.5",
"jwks-rsa": "^1.3.0",
server.auth.strategy('auth0_jwk', 'jwt', {
    complete: true,
    key: jwksRsa.hapiJwt2KeyAsync({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
    }),
    validate: async function() {
      // TODO: Implement a validation
      return {
        isValid: true,
      };
    },
    headerKey: 'authorization',
    tokenType: 'Bearer',
    verifyOptions: {
      issuer: `https://${process.env.AUTH0_DOMAIN}/`,
      algorithms: ['RS256'],
    },
  });

@Marsup Marsup added follow instructions The issue failed to follow instructions, try again and removed missing discussion labels Sep 20, 2019
@lock lock bot locked as resolved and limited conversation to collaborators Mar 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
follow instructions The issue failed to follow instructions, try again
Projects
None yet
Development

No branches or pull requests

9 participants