Troubleshooting 403 error with Keycloak authentication in containerized Node.js app

I’m having trouble with my Keycloak setup. My Node.js app works fine locally but gives a 403 error when containerized. Here’s what I’ve got:

  • Keycloak server in Docker on my NAS
  • Node.js/Express backend using keycloak-connect
  • Service Account Roles for auth
  • Both containers on the same Docker network

My config looks like this:

const KeycloakAuth = require('keycloak-connect');

const authConfig = new KeycloakAuth({}, {
  "realm": process.env.REALM_NAME,
  "bearer-only": true,
  "auth-server-url": process.env.AUTH_URL,
  "ssl-required": "none",
  "resource": process.env.CLIENT_ID
});

module.exports = authConfig;

I use it like this:

const authConfig = require("./config/auth-setup");
app.use(authConfig.middleware());

router.post("/api/connect", authConfig.protect(), handleConnection);

Any ideas why it’s not working in the container? The tokens look good, and I can reach Keycloak from the backend container. No specific errors in the logs either. What am I missing?

hey alex, had similar issue. check if ur container has correct env vars set. sometimes they dont carry over. also, double-check ur keycloak client config - make sure the redirect URI matches ur containerized app’s URL. good luck troubleshooting!

I encountered a similar issue when containerizing a Node.js application with Keycloak authentication. One often overlooked aspect is the network configuration. Ensure that your Docker network is properly set up and that the containers can communicate effectively. Additionally, verify that the Keycloak server’s URL is correctly accessible from within the containerized environment. It’s also worth checking the Keycloak server logs for any authentication failures or connection issues. If the problem persists, consider implementing more detailed logging in your Node.js application to pinpoint where exactly the 403 error is occurring in the authentication flow.

Hmm, intresting problem! have u tried checkin the time sync between ur containers? sometimes auth fails if clocks r off. also, maybe ur container’s ip is different from local? keycloak might be expectin a specific origin. can u try addin some debug logs to see where exactly its failin?