Keycloak-connect returns 403, when provided with bearer token

My setup is made up of both a Vue.js app and a a nodej.js/express base API server. I have been been trying to follow the example on the quickstart examples, but I am getting 403 error.

From the front-end I pass a the keycloak.token, by means of an Authorization: Bearer <token> header.

On the server side I have protected my route via:

import KeycloakConnect from 'keycloak-connect';

const keycloak = new KeycloakConnect ({ });

// where staff is a role
router.use('/api', keycloak.protect('staff'), apiRoutes);
// also tried
router.use('/api', keycloak.protect('realm:staff'), apiRoutes);

Because we will be running load balanced, we have opted to avoid using a session.

I am not seeing any debug mode to provide more details.

Initial exploration suggested the bearer token may not even be checked, suggesting a possible config issue. I am diving much more into the source code than I wish, due to lack of documentation, so I am hoping someone can get me out of this rabbit hole with a few good pointers.

Update: while still having not found the solution, I did notice I had forgotten to initialise the keycloak middleware at launch and the client-import.json file. Now it is checking the bearer token, but still getting the 403:

    app.use(keycloak.middleware({
        logout: '/auth/logout',
        admin: '/'
    }));

I ended up just debugging the library, which really could do with some debug messages, since a number of error scenarios are just swallowed. It could also benefit from async/await, but I digress.

The clue of my final issue was first via some extra logging in Keycloak.prototype.getGrant of the keycloak.js file, which indicated:

Error: Grant validation failed. Reason: invalid token (wrong type)

Then, following the source of the exception to grant-manager and logging in the block that was generating that message, it turns out it wants the keycloak.token and not the keycloak.idtoken as bearer value.

Based on more experimenting, my observations, for anyone else:

  • Don’t forget to initialise the middleware, otherwise it won’t even do anything with the auth
  • client-import.json wasn’t being used
  • Be sure to provide the right token as bearer
    • Opinion: that token is large, so it may just better to do an initial auth handshake and then use a local token?
  • Include the keycloak.json or provide the values via the constructor
  • The 403 error seems to be catch all error, so there is no apparent distinction between authentication, authorisation or some other scenario.
  • The keycloak.d.ts file provides some useful documentation
1 Like

is a pain the troubleshoot with the library, doesn’t have any debugging info, i’ve been just consoling.log step by step an error only happening in production.