Pages

Sunday, April 16, 2023

Keycloak: Client roles spring boot

Keycloak is an open-source Identity and Access Management (IAM) solution that provides authentication and authorization services for applications and services. The Keycloak Admin Console is a web-based user interface that allows administrators to manage and configure the Keycloak server.

To access the Keycloak Admin Console, follow these steps:
  1. Open a web browser and go to the URL where Keycloak is installed.
  2. Click on the "Administration Console" link located in the top-right corner of the login screen.
  3. Enter your administrative username and password to log in.
  4. Once you have logged in, you will be presented with the Keycloak Admin Console dashboard, where you can manage and configure your Keycloak instance.

From the Admin Console, you can perform a wide range of tasks, such as:

  • Create and manage users and groups
  • Configure identity providers and client applications
  • Define authentication and authorization policies
  • Monitor server performance and logs
  • Configure themes and templates
  • And much more.
Overall, the Keycloak Admin Console provides a powerful set of tools for managing and securing your applications and services.

Create client roles using admin console:

Login to the admin console http://localhost:8080/admin/ using your admin credentials. Switch to the realm of your client. Click on your client ID from the list of ‘clients’ that you can see when clicking on Clients button in the left side navigation bar. In the next screen switch to ‘Roles’ tab and click on ‘Add Role’ button.








                                                                                                                                                                            
We have successfully created a client role, let us add this to a user. For that click on Users button on the left side navigation bar and then click on the user id or edit button which is corresponding to the preferred user. Then go to Role Mappings tab; From the Client Roles drop down button select your preferred client; then select the role from the Available Roles area and click on Add Selected to assign that particular client role to that particular user.      


Time to move on to the interesting part! From now we will look into how we can do all the above works programmatically in Spring Boot using Keycloak admin client API. Let’s start.

With Spring Boot application


Open your preferred browser and go to start.spring.io and create a new spring boot application. Make sure the following dependencies are added in pom.xml file.


<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
<version>11.0.3</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.1.3.Final</version>
</dependency>         


Yes it is coding time!! Let’s first have a look on how to get a Keycloak instance.

Controller for create roles, Getting all clients level roles, and make role as composite.

@RestController
@Log4j2
@RequestMapping(RefoConstant.BASE_ROLE_URL)
public class RoleController {

private final RoleService roleService;

public RoleController(RoleService roleService) {
this.roleService = roleService;
}

@GetMapping("/fetchAllRoles")
@Operation(summary = "fetchAllRoles", security = @SecurityRequirement(name = "AccessToken"))
public List<RoleRepresentation> getAllRoles(HttpServletRequest request){
return roleService.getAllRoles();
}

@PostMapping("/createRole")
@Operation(summary = "createRole", security = @SecurityRequirement(name = "AccessToken"))
public RoleResponseDTO createRole(HttpServletRequest servletRequest,@RequestBody @NotNull RoleRequestDTO request){
return roleService.createRole(request);
}

@GetMapping("/{name}")
@Operation(summary = "createRole", security = @SecurityRequirement(name = "AccessToken"))
public RoleRepresentation getRoleByName(HttpServletRequest servletRequest,
@PathVariable("name") String name) throws RefoException {
return roleService.getRoleByName(name);
}

}      

Role Service Interface.

public interface RoleService {
RoleResponseDTO createRole(RoleRequestDTO request);

RoleRepresentation getRoleByName(String name) throws RefoException;

List<RoleRepresentation> getAllRoles();
}

Fine, if it is successful we can do the magic with our keycloak instance. Follow on folks. The below code snippet shows how we can get all the available roles for the particular client registered in our keycloak server.



@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

private final Keycloak keycloak;
private final KeycloakClientConfig keycloakClientConfig;

public RoleServiceImpl(Keycloak keycloak, KeycloakClientConfig keycloakClientConfig) {
this.keycloak = keycloak;
this.keycloakClientConfig = keycloakClientConfig;
}

public List<RoleRepresentation> getAllRoles() {
return keycloak.realm(keycloakClientConfig.getRealm())
.roles().list();
}

public RoleRepresentation getRoleByName(String roleName) throws RefoException {
try{
return keycloak.realm(keycloakClientConfig.getRealm())
.roles().get(roleName).toRepresentation();
}catch(Exception e){
throw new RefoException(ExceptionMessageCode.REFO_ROLE_0001,String.format("%s doesn't exists!",roleName));
}
}

@Override
public RoleResponseDTO createRole(RoleRequestDTO request){
RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName(request.getName());
roleRepresentation.setContainerId(keycloakClientConfig.getRealm());
try{
keycloak.realm(keycloakClientConfig.getRealm())
.roles().create(roleRepresentation);
return RoleResponseDTO.builder().message("Role created successfully.").build();
}catch (ClientErrorException cee){
if(cee.getResponse().getStatus()==409){
return RoleResponseDTO.builder().message("Role already exists.").build();
}else {
return RoleResponseDTO.builder().message("Role not created.").build();
}
}
}
}


                                                                                                                                           
Hope you enjoyed this blog. Follow me to get to know some more interesting stuffs like this. Please don’t forget to give some clapping.

No comments:

Post a Comment