【问题标题】:How to get UserGroups from KeyCloak and print them in Java如何从 KeyCloak 获取用户组并用 Java 打印它们
【发布时间】:2021-02-24 19:22:21
【问题描述】:

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

这是我的 SecurityConfiguration 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;
    }

【问题讨论】:

    标签: spring-boot spring-security keycloak spring-security-oauth2


    【解决方案1】:

    要在 Java 中列出 Keycloak 领域内的所有用户组,您可以使用 Keycloak 提供的 Keycloak Admin REST client library 并在公共 Maven 存储库中可用:groupId=org.keycloak, artifactId=keycloak-admin-client, 版本是/应该是相同的作为您的 Keycloak 服务器(至少相同的主要和次要部分)。基本上,使用这个库,您创建一个 Keycloak 实例,然后选择领域,并从那里获取组,例如如 Server Developer guide 部分 Admin REST API > 使用 Java 的示例the GroupTest test case on Keycloak github(方法 searchAndCountGroups)中所示。 p>

    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.
    }
    

    【讨论】:

    • 我收到此错误'groups' has protected access in 'org.keycloak.representations.idm.RealmRepresentation'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    相关资源
    最近更新 更多