如何从 KeyCloak 获取用户组并在 Java 中打印它们

How to get UserGroups from KeyCloak and print them in Java

我有一个 spring-boot 应用程序,它使用 spring-boot-starter-security 并且我已将 Keycloak 集成到 Spring Boot 应用程序以进行身份​​验证/授权。我想从 KeyCloak 获取用户组并将它们显示在我的 Spring 启动应用程序中。你知道从 KeyCloak 获取用户组并在屏幕上显示它们的方法吗?应该有一个实现来提供它?

这是我的安全配置 java :

  @Configuration
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  @EnableWebSecurity
  public class KeyCloakSecurityConfig extends WebSecurityConfigurerAdapter {

 private final KeycloakJwtConfig keycloakJwtConfig;



  @Override
  public void configure(final HttpSecurity http) throws Exception {
   http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .csrf().disable()
    .formLogin().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.GET, "/actuator/health").permitAll()
    .anyRequest().authenticated()
    .and()
    .oauth2ResourceServer()
    .jwt()
    .jwtAuthenticationConverter(new JwtAuthoritiesExtractor())
    .jwkSetUri(this.keycloakJwtConfig.jwkSetUri());
   }

 @Autowired
public SecurityConfiguration(final KeycloakJwtConfig   keycloakJwtConfig) {
 keycloakJwtConfig = keycloakJwtConfig;
    }

要列出 Java 中 Keycloak 领域内的所有用户组,您可以使用 Keycloak Admin REST client library provided with Keycloak and available in public Maven repositories: groupId=org.keycloak, artifactId=keycloak-admin-client, version is/should be the same as your Keycloak server (at least the same major and minor parts). Basically, with this library, you create a Keycloak instance, then select the realm, and get the groups from there, e.g. as shown in the Server Developer guide, section Admin REST API > Example using Java and the GroupTest test case on Keycloak github(方法 searchAndCountGroups)。

Keycloak keycloak = Keycloak.getInstance(
    "http://localhost:8080/auth",
    "master",
    "admin",
    "password",
    "admin-cli");
RealmRepresentation realm = keycloak.realm("master").toRepresentation();

for (GroupRepresentation group : realm.groups().groups()) 
{
  // Display group.getId(), group.getName(), etc.
}