I have a spring-boot application which uses spring-boot-starter-security and I have integrated Keycloak to Spring Boot application for authentication / authorization purposes. I want to fetch UserGroups from KeyCloak and display them in my SpringBoot Application. Do you know a way to fetch UserGroups from KeyCloak and display them at screen? There should be an implementation to provide it ?
This is my 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;
}
For listing all user groups within a Keycloak realm in Java, you may use 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 (method 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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With