How to programmatically create a keycloak client role and assign to a user

I want to programmatically create a keycloak client role and dynamically assign to the user. Below is my code for creating user

UserRepresentation user = new UserRepresentation();
user.setEmail("xxxxx@xxx.com");
user.setUsername("xxxx");
user.setFirstName("xxx");
user.setLastName("m");
user.setEnabled(true);
Response response = kc.realm("YYYYY").users().create(user);

      

+3


source to share


1 answer


Here is a solution for your request (not very pretty, but it works):

// Get keycloak client
Keycloak kc = Keycloak.getInstance("http://localhost:8080/auth",
                "master", "admin", "admin", "admin-cli");

// Create the role
RoleRepresentation clientRoleRepresentation = new RoleRepresentation();
clientRoleRepresentation.setName("client_role");
clientRoleRepresentation.setClientRole(true);
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation ->
    kc.realm("RealmID").clients().get(clientRepresentation.getId()).roles().create(clientRoleRepresentation)
);

// Create the user
UserRepresentation user = new UserRepresentation();
user.setUsername("test");
user.setEnabled(true);
Response response = kc.realm("RealmID").users().create(user);
String userId = getCreatedId(response);

// Assign role to the user
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation -> {
    RoleRepresentation savedRoleRepresentation = kc.realm("RealmID").clients()
            .get(clientRepresentation.getId()).roles().get("client_role").toRepresentation();
    kc.realm("RealmID").users().get(userId).roles().clientLevel(clientRepresentation.getId())
            .add(asList(savedRoleRepresentation));
});

// Update credentials to make sure, that the user can log in
UserResource userResource = kc.realm("RealmID").users().get(userId);
userResource.resetPassword(credential);

      



With help method:

private String getCreatedId(Response response) {
    URI location = response.getLocation();
    if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new WebApplicationException("Create method returned status " +
                statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201)", response);
    }
    if (location == null) {
        return null;
    }
    String path = location.getPath();
    return path.substring(path.lastIndexOf('/') + 1);
}

      

+4


source







All Articles