Techniques to Integrate Authentication and Authorization in Spring Boot Using Keycloak Admin Client and Resteasy
In modern enterprise systems, integrating secure authentication and authorization isn’t just an architectural afterthought — it’s a survival requirement. The more distributed and API-driven your system becomes, the more you need a central identit...

I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
1. Introduction
1.1. Why Keycloak with Spring Boot?
- Spring Security: for enforcing access control.
- Keycloak Spring Adapter: for token verification.
- Keycloak Admin Client + Resteasy: for programmatic interaction with Keycloak’s REST API.
1.2. Architectural Overview
- A client (e.g., frontend or mobile) logs in via Keycloak and obtains an access token.
- The Spring Boot backend validates the token and authorizes access.
- Certain administrative actions (creating users, assigning roles, etc.) are handled by the Spring Boot backend using the Keycloak Admin Client.
- The Admin Client communicates with Keycloak’s REST endpoints through Resteasy, eliminating the need to manually handle low-level HTTP logic.
2. Implementation with Example
2.1. Dependencies
pom.xml, add:
<dependencies>
<dependency>
<groupid>org.keycloak</groupid>
<artifactid>keycloak-admin-client</artifactid>
<version>25.0.0</version>
</dependency>
<dependency>
<groupid>org.jboss.resteasy</groupid>
<artifactid>resteasy-client</artifactid>
<version>6.2.5.Final</version>
</dependency>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>
</dependencies>
keycloak-admin-client provides the Java binding for interacting with Keycloak’s Admin REST API, and resteasy-client acts as the HTTP layer that powers it.
2.2. Configuration
@Configuration
public class KeycloakConfig {
@Value("${keycloak.server.url}")
private String serverUrl;
@Value("${keycloak.realm}")
private String realm;
@Value("${keycloak.client.id}")
private String clientId;
@Value("${keycloak.client.secret}")
private String clientSecret;
@Bean
public Keycloak keycloak() {
return KeycloakBuilder.builder()
.serverUrl(serverUrl)
.realm("master")
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
@Bean
public RealmResource realmResource(Keycloak keycloak) {
return keycloak.realm(realm);
}
}
- We connect using the client credentials grant, meaning our service authenticates as a trusted Keycloak client.
RealmResourceprovides direct access to user and role management methods within a realm.
2.3. Example: Programmatically Creating a User
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
private final RealmResource realmResource;
@PostMapping
public ResponseEntity<string> createUser(@RequestBody CreateUserRequest req) {
UserRepresentation user = new UserRepresentation();
user.setUsername(req.getUsername());
user.setEmail(req.getEmail());
user.setEnabled(true);
Response response = realmResource.users().create(user);
if (response.getStatus() == 201) {
return ResponseEntity.ok("User created successfully!");
} else {
return ResponseEntity.status(response.getStatus()).body("Failed to create user");
}
}
}
CreateUserRequest DTO:
@Data
public class CreateUserRequest {
private String username;
private String email;
}
users().create() endpoint behind the scenes via Resteasy, serializing the payload to JSON and handling authentication headers automatically.
2.4. Assigning Roles
public void assignRole(String userId, String roleName) {
RoleRepresentation role = realmResource.roles().get(roleName).toRepresentation();
realmResource.users().get(userId).roles().realmLevel().add(Collections.singletonList(role));
}
.remove(Collections.singletonList(role)).
3. Advanced Discussion
3.1. Handling Tokens and Security
- Store the admin client credentials securely (e.g., via Vault).
- Use a service account for automation tasks only.
- Restrict access to management endpoints via Spring Security annotations like:
@PreAuthorize("hasRole('ADMIN')")
spring-boot-starter adapter for runtime authentication validation, ensuring users’ access tokens are verified via Keycloak’s introspection endpoint or public key.
3.2. Error Handling and Retry Logic
createUser and assignRole actions.
3.3. Integration with CI/CD and Microservices
4. Conclusion
Read more at : Techniques to Integrate Authentication and Authorization in Spring Boot Using Keycloak Admin Client and Resteasy





