Keycloak with Node.js API fails through Docker

2020-06-06 07:30发布

问题:

I've got a Node.js Rest API that's integrated with Keycloak. When I run the API locally with no docker everything works fine. But whenever I run the API through my docker image I get an error 403 (forbidden). I've already made sure that my container can connect (ping/telnet) my Keycloak server. Any ideas what might be causing the problem?

I'm using the following lib to integrate with Keycloak: https://github.com/keycloak/keycloak-nodejs-connect

Keycloak middleware:

const session = require("express-session");
const Keycloak = require("keycloak-connect");

function configureKeycloack(app) {
  // session
  const memoryStore = new session.MemoryStore();
  app.use(
    session({
      secret: "secret-here",
      resave: false,
      saveUninitialized: true,
      store: memoryStore
    })
  );
  const keycloak = new Keycloak({
    store: memoryStore
  });
  app.use(
    keycloak.middleware({
      logout: "/logout",
      admin: "/"
    })
  );
  // Middleware
  app.use("/api/**", keycloak.protect());
}

module.exports = configureKeycloack;

keycloak.json

{
    "realm": "my-realm",
    "bearer-only": true,
    "auth-server-url": "http://172.18.0.3:8080/auth",
    "ssl-required": "external",
    "resource": "communication-plan",
    "verify-token-audience": true,
    "credentials": {
        "secret": "secret-goes-here...."
    },
    "confidential-port": 0,
    "policy-enforcer": {}
}

Dockerfile

FROM node:10.16.3
WORKDIR /usr/src/app
COPY package*.json ./
COPY .npmrc ./
RUN npm install
COPY . .
EXPOSE 3001
CMD npx sequelize db:migrate && node src/index.js

回答1:

I succeeded to find a workaround by using the host networking functionality in the container. As described in this post related to a similar issue with POSTMAN, I pass --network host to the docker run command and it works