小编典典

Docker(Spring Boot或Thorntail)和Keycloak

spring-boot

我在docker容器中都运行Spring Boot和Keycloak时遇到问题。

我首先在docker中运行带有MySQL的Keycloak和db。

services:
  mysql:
    image: mysql:5.7
    container_name: mysql
    volumes:
      - mysql_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: keycloak
      MYSQL_USER: keycloak
      MYSQL_PASSWORD: password
    networks:
      - testNetwork

  keycloak:
    image: jboss/keycloak
    container_name: keycloak
    restart: on-failure
    volumes:
      - ./config:/config/
    environment:
      DB_VENDOR: MYSQL
      DB_ADDR: mysql
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_PASSWORD: password
      KEYCLOAK_USER: xxx
      KEYCLOAK_PASSWORD: yyy
      KEYCLOAK_IMPORT_REALM: /keycloak/import/realm-import.json
    ports:
      - 8180:8080
    depends_on:
      - mysql
    networks:
      - testNetwork

然后,我添加了我的领域(SpringBootKeycloak),我的客户端(testclient)和一个角色为’user’的用户。之后,我在Spring-
boot-application中添加了spring-security。并编辑了我的application.yml

spring:
  main:
    banner-mode: 'off'
  application:
    name: testclient
    version: @project.version@
  jpa:
    hibernate:
      ddl-auto: create
  datasource:
    url: jdbc:h2:mem:testclient;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: xxx
    password: xxx
keycloak:
  auth-server-url: http://localhost:8180/auth
  realm: SpringBootKeycloak
  resource: testclient
  public-client: true
  principal-attribute: preferred_username
  security-constraints:
    - authRoles:
      - user
      securityCollections:
        - patterns:
          - /*
server:
  port: ${port:8090}
  rest:
    path: testclient

根据我添加了我的SecurityConfig:

  /**
   * Secure appropriate endpoints
   */
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.authorizeRequests()
        .antMatchers("/*").hasRole("user") // only user with role user are allowed to access
        .anyRequest().permitAll();
  }

在本地运行SpringBoot-
Application运行正常。我必须使用keycloak登录并重定向到localhost:8090。但是,当我将SpringBoot-
Application添加到我的docker-compose并在容器中启动它时,我仍然会进入keycloak进行登录,但是当我应该重定向时会得到403。

  testclient:
    image: testclient
    container_name: testclient
    environment:
      JAVA_OPTS: "-agentlib:jdwp=transport=dt_socket,address=5005,server=y,suspend=n"
    build:
      context: testclient-application
    ports:
      - 8090:8090
      - 5006:5005
    networks:
      - testNetwork

具有以下容器日志:

{"@timestamp":"2018-08-16T11:50:11.530+00:00","@version":"1","message":"failed to turn code into token","logger_name":"org.keycloak.adapters.OAuthRequestAuthenticator","thread_name":"http-nio-8090-exec-6","level":"ERROR","level_value":40000,"stack_trace":"java.net.ConnectException: Connection refused (Connection refused)\n\tat java.net.PlainSocketImpl.socketConnect(Native Method)\n\tat java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)\n\tat java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)\n\tat java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)\n\tat java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)\n\tat java.net.Socket.connect(Socket.java:589)\n\tat org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)\n\tat org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)\n\tat org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:144)\n\tat org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:134)\n\tat org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:610)\n\tat org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:445)\n\tat org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)\n\tat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)\n\tat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)\n\tat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)\n\tat org.keycloak.adapters.ServerRequest.invokeAccessCodeToToken(ServerRequest.java:111)\n\tat org.keycloak.adapters.OAuthRequestAuthenticator.resolveCode(OAuthRequestAuthenticator.java:336)\n\tat org.keycloak.adapters.OAuthRequestAuthenticator.authenticate(OAuthRequestAuthenticator.java:281)\n\tat org.keycloak.adapters.RequestAuthenticator.authenticate(RequestAuthenticator.java:139)\n\tat org.keycloak.adapters.tomcat.AbstractKeycloakAuthenticatorValve.authenticateInternal(AbstractKeycloakAuthenticatorValve.java:203)\n\tat org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve.authenticate(KeycloakAuthenticatorValve.java:50)\n\tat org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve.doAuthenticate(KeycloakAuthenticatorValve.java:57)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:575)\n\tat org.keycloak.adapters.tomcat.AbstractKeycloakAuthenticatorValve.invoke(AbstractKeycloakAuthenticatorValve.java:181)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.lang.Thread.run(Thread.java:748)\n","app":"testclient","version":"1.0.0-SNAPSHOT"}

我不知道该怎么解决…

编辑1:更多信息:我在Windows上运行docker。

编辑2:一种解决方案

我的工作解决方案包含以下内容:

  1. 步骤,将密钥斗篷添加为主机

为了使一切正常,您需要确保将以下内容添加到您的主机文件中(在Mac / Linux中为/ etc / hosts,在Windows中为c:\
Windows \ System32 \ Drivers \ etc \ hosts)。

127.0.0.1密钥斗篷

这是因为您将使用计算机上的浏览器(名称为localhost或127.0.0.1)访问应用程序,但是在Docker内部它将在自己的容器(名称为keycloak)中运行。

内部Docker端口和发布的端口必须相同:

services:
  mysql:
    image: mysql:5.7
    container_name: mysql
    volumes:
      - mysql_data:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: keycloak
      MYSQL_USER: keycloak
      MYSQL_PASSWORD: password
    networks:
      - testNetwork

  keycloak:
    image: jboss/keycloak
    container_name: keycloak
    restart: on-failure
    volumes:
      - ./config:/config/
    environment:
      DB_VENDOR: MYSQL
      DB_ADDR: mysql
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_PASSWORD: password
      KEYCLOAK_USER: xxx
      KEYCLOAK_PASSWORD: yyy
      KEYCLOAK_IMPORT_REALM: /keycloak/import/realm-import.json
    ports:
      - 8080:8080   <--- edited
    depends_on:
      - mysql
    networks:
      - testNetwork

步骤3:在application.yml中为Spring Boot编辑的auth-server-url中的密钥库定义:

    keycloak:
  realm: SpringBootKeycloak
  auth-server-url: http://keycloak:8080/auth   <--- edited
  resource: testclient
  public-client: true
  security-constraints:
    - authRoles:
      - user
      securityCollections:
        - patterns:
          - /*
  ssl-required: external
  confidential-port: 0

该解决方案带来的丑陋之处:您无法将Docker
Port映射到另一个端口以从url访问。端口:-8080:8080我花了大量时间测试其他组合,结果访问URL端口必须与内部docker端口相同(在我的情况下为8080)。

编辑4:

同样的事情正在与Thorntail合作。

要更改Keycloak的端口,请添加…

environment:
  JAVA_OPTS: "-Djboss.socket.binding.port-offset=10 -Xms64m -Xmx512m -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=256m
  -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true"

…用于docker-compose中的密钥斗篷。-Djboss.socket.binding.port-offset =
10设置默认端口(8080)+偏移量(10),其余均为密钥斗篷的默认值。不要忘记编辑“端口”和“ auth-server-url”


阅读 400

收藏
2020-05-30

共1个答案

小编典典

我认为你的问题是auth-server-url: http://localhost:8180/authlocalhost当您的应用程序在docker容器中运行时,这实际上具有不同的含义。

在容器内部,它必须是容器的名称,即keycloak。这有点尴尬,因为当您从要使用的主机连接到keycloak时,localhost但令牌发行者的URL必须与请求令牌的URL匹配(否则令牌被拒绝),因此最终放入keycloak您的etc
/ hosts文件。

您在这个问题上相处得很好-我在Activiti工作中遇到了这个问题。您可以找到以同样方式处理它JHipster项目 -他们说:

为了使一切正常,您需要确保将以下内容添加到您的主机文件中(/etc/hosts在Mac /
Linux上,c:\Windows\System32\Drivers\etc\hosts在Windows上)。

127.0.0.1 keycloak

这是因为您将使用计算机上的浏览器(名称为localhost127.0.0.1)访问应用程序,但是在Docker内部它将在自己的容器中运行,名称为keycloak

2020-05-30