GVKun编程网logo

Keycloak和Spring Boot Rest API-用户特定的数据策略(springboot用户信息的存取)

14

最近很多小伙伴都在问Keycloak和SpringBootRestAPI-用户特定的数据策略和springboot用户信息的存取这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展bo

最近很多小伙伴都在问Keycloak和Spring Boot Rest API-用户特定的数据策略springboot用户信息的存取这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展bootstrap之PressKeyCode&&LongPressKeyCode、Docker(Spring Boot或Thorntail)和Keycloak、java – Docker(Spring Boot或Thorntail)和Keycloak、java – Spring Boot – KeyCloak指向403禁止等相关知识,下面开始了哦!

本文目录一览:

Keycloak和Spring Boot Rest API-用户特定的数据策略(springboot用户信息的存取)

Keycloak和Spring Boot Rest API-用户特定的数据策略(springboot用户信息的存取)

Keycloak是一种用户联合身份解决方案,与其他引用它的系统(例如,用于授权)独立(独立)运行,该系统具有自己的数据库。

问题:如何在我的REST API数据库中引用/创建用户特定的数据?如何在其余api数据库中引用用户以获取特定于用户的数据?

像Post这样的表

标题,日期,内容, 作者 (此处是对用户的引用)

答案1

小编典典

在Java
EE应用程序中,我们有类似的要求,用户可以在其中通过JSF网站创建数据。数据与审核信息(用户名,用户ID,时间戳等)存储在postrgesql中,因此我想要实现的正是这些。

我们仅通过通过会话中当前可用的访问令牌检索信息来实现。我们还在keycloak本身中引入了一个新的用户属性,它是一个自定义帐户ID。用户在密钥斗篷GUI上进行设置,然后我们通过accessToken.getOtherClaims()。get(“
ACCOUNT_ID”)进行检索,以查询特定于用户的数据。

令牌本身在过滤器中处理,并在另一个bean中使用,以检索看起来像

@WebFilter(value = "/*")public class RefreshTokenFilter implements Filter {  @Inject  private ServletOAuthClient oauthClient;  @Inject  private UserData userData;  @Context  KeycloakSecurityContext  sc;  @Override  public void init(FilterConfig filterConfig) throws ServletException {  }  @Override  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {    HttpServletRequest request = (HttpServletRequest) servletRequest;    HttpServletResponse response = (HttpServletResponse) servletResponse;    if (request.getUserPrincipal() != null) {      KeycloakSecurityContext keycloakSecurityContext = ((KeycloakPrincipal) request.getUserPrincipal()).getKeycloakSecurityContext();      userData.setAccessToken(keycloakSecurityContext.getToken());      userData.setIdToken(keycloakSecurityContext.getIdToken());    }    filterChain.doFilter(request, response);  }  @Override  public void destroy() {  }}

这里有处理数据访问的bean

@SessionScoped@Named("userData")public class UserData implements Serializable {  private static final String ACCOUNT_ID = "accountId";  private AccessToken accessToken;  private IDToken idToken;  public String getUserFullName() {    return isHasAccessToken() ? accessToken.getName() : null;  }  public String getUserName() {    return isHasAccessToken() ? accessToken.getPreferredUsername() : null;  }  public String getUserId() {    return isHasAccessToken() ? accessToken.getSubject() : null;  }  public String getRoles() {    StringBuilder roles = new StringBuilder();    if (isHasAccessToken()) {      accessToken.getRealmAccess().getRoles().stream().forEach(s -> roles.append(s).append(" "));    }    return roles.toString();  }  public boolean hasApplicationRole(String role) {    return accessToken.getRealmAccess().isUserInRole(role);  }  public boolean isHasAccessToken() {    return accessToken != null;  }  public List<String> getAccountIds() {    return isHasAccessToken() && accessToken.getOtherClaims().get(ACCOUNT_ID)!=null ? (List<String>) accessToken.getOtherClaims().get(ACCOUNT_ID) : new ArrayList<>();  }  public void setAccessToken(AccessToken accessToken) {    this.accessToken = accessToken;  }  public void setIdToken(IDToken idToken) {    this.idToken = idToken;  }}

我认为spring启动会为您提供类似的选项来处理KeycloakSecurityContext。

bootstrap之PressKeyCode&&LongPressKeyCode

bootstrap之PressKeyCode&&LongPressKeyCode

总结

以上是小编为你收集整理的bootstrap之PressKeyCode&&LongPressKeyCode全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Docker(Spring Boot或Thorntail)和Keycloak

Docker(Spring Boot或Thorntail)和Keycloak

我在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: xxxkeycloak:  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”

答案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

java – Docker(Spring Boot或Thorntail)和Keycloak

java – Docker(Spring Boot或Thorntail)和Keycloak

我在Docker容器中运行Spring Boot和Keycloak时出现问题.

我开始使用Keycloak和MysqL作为db在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:
      - 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:解决方案

我的工作解决方案包含以

>步骤,添加keycloak作为主机

To make things work, you’ll need to make sure to add the following to your hosts file (/etc/hosts on Mac/Linux, c:\Windows\System32\Drivers\etc\hosts on Windows).

127.0.0.1 keycloak

This is because you will access your application with a browser on your machine (which name is localhost, or 127.0.0.1), but inside Docker it will run in its own container, which name is 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中的keycloak定义,用于Spring启动编辑的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端口映射到另一个端口以从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中的keycloak.
-Djboss.socket.binding.port-offset = 10设置默认端口(8080)偏移量(10)
其余是keycloak的默认值.
别忘了编辑“ports”和“auth-server-url”

解决方法:

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

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

你和这个问题很好 – 我遇到了这个working with Activiti.你可以找到JHipster project dealing with it in the same way – 他们说:

To make things work, you’ll need to make sure to add the following to your hosts file (/etc/hosts on Mac/Linux, c:\Windows\System32\Drivers\etc\hosts on Windows).

127.0.0.1 keycloak

This is because you will access your application with a browser on your machine (which name is localhost, or 127.0.0.1), but inside Docker it will run in its own container, which name is keycloak.

java – Spring Boot – KeyCloak指向403禁止

java – Spring Boot – KeyCloak指向403禁止

我是Keycloak的新手,我正在使用官方教程项目
https://github.com/sebastienblanc/spring-boot-keycloak-tutorial

为了与Springboot应用程序集成,我已经成功设置了KeyCloak服务器,并且Spring引导应用程序也指向我在KeyCloak上创建的Realm上创建的客户端应用程序,之后提供了它指向禁止页面的正确凭据.

@Controller
class ProductController {

@GetMapping(path = "/products")
public String getProducts(Model model){
    model.addAttribute("products",Arrays.asList("iPad","iPhone","iPod"));
    return "products";
}

@GetMapping(path = "/logout")
public String logout(HttpServletRequest request) throws servletexception {
    request.logout();
    return "/";
}
}

Application.properties文件

keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=springdemo
keycloak.resource=product-app
keycloak.public-client=true

keycloak.security-constraints[0].authRoles[0]=testuser
keycloak.security-
constraints[0].securityCollections[0].patterns[0]=/products/*

server.port=8081

我没有从KeyCloak控制台或spring嵌入式tomcat控制台收到任何错误消息.

Check the tomcat console here – no error

enter image description here

谢谢.

最佳答案
我觉得你有一个错字
keycloak.security-constraints [0] .authRoles [0] = testuser,你应该在这里指定角色而不是用户.
如果您按照博客说明进行操作,则应该是:
keycloak.security约束[0] .authRoles [0] =用户

今天关于Keycloak和Spring Boot Rest API-用户特定的数据策略springboot用户信息的存取的分享就到这里,希望大家有所收获,若想了解更多关于bootstrap之PressKeyCode&&LongPressKeyCode、Docker(Spring Boot或Thorntail)和Keycloak、java – Docker(Spring Boot或Thorntail)和Keycloak、java – Spring Boot – KeyCloak指向403禁止等相关知识,可以在本站进行查询。

本文标签: