boycod3
boycod3

Reputation: 5319

Keycloak create user role

I have inserted both new user and role to the keycloak. But how can I connect the user and role entity like user-role

Keycloak kc = KeycloakBuilder.builder()
                .serverUrl("http://localhost:8080/auth")
                .realm("master")
                .username("admin")
                .password("admin")
                .clientId("admin-cli")
                .resteasyClient(
                    new ResteasyClientBuilder()
                        .connectionPoolSize(10).build()
                ).build();
//creating role
RoleRepresentation roleRepresentation = new RoleRepresentation();
        roleRepresentation.setName("latest_role");
        kc.realm("master").roles().create(roleRepresentation);
//creating user
UserRepresentation user = new UserRepresentation();
        user.setUsername("anoop");
        user.setFirstName("anoop");
        user.setLastName("anoop");
        user.setEnabled(true);
        user.setCredentials(Arrays.asList(credential));
        kc.realm("master").users().create(user);

Upvotes: 2

Views: 6778

Answers (2)

David Klassen
David Klassen

Reputation: 296

This seems to be an not trivial issue. Normally I would expect this functionality in the user.setRealmRoles(roleRepresentation)like in this example. But that wasn't working for me.

Instead I used this function to add the roleRepresentation to the user.

RoleRepresentation savedRoleRepresentation = kc.realm("master").roles()
        .get("latest_role").toRepresentation();
kc.realm("master").users().get(userId).roles().realmLevel()
        .add(asList(savedRoleRepresentation));

Complete code:

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

RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName("latest_role");
kc.realm("Test").roles().create(roleRepresentation);

UserRepresentation user = new UserRepresentation();
user.setUsername("test");
user.setFirstName("test");
user.setLastName("test");
user.setEnabled(true);
user.setCredentials(Arrays.asList(credential));

Response response = kc.realm("Test").users().create(user);
String userId = getCreatedId(response);

System.out.println("Testuser created.... verify in keycloak!");

RoleRepresentation savedRoleRepresentation = kc.realm("Test").roles()
        .get("latest_role").toRepresentation();
kc.realm("Test").users().get(userId).roles().realmLevel()
        .add(asList(savedRoleRepresentation));


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);
}

EDIT:

It seems like the credentials aren't saved for the user. To force keycloak to save them, you have to reset the password with:

UserResource userResource = kc.realm("Test").users().get(userId);
userResource.resetPassword(credential);

Upvotes: 5

boycod3
boycod3

Reputation: 5319

UserRepresentation user = new UserRepresentation();
    user.setEmail("[email protected]");
    user.setUsername("naveenm555");
    user.setFirstName("naveen");
    user.setLastName("m");
    user.setEnabled(true);
    Response response = kc.realm("appscook").users().create(user);
    System.out.println("user created.... verify in keycloak!");
    String userId = getCreatedId(response);

    UserResource userResource=kc.realm("appscook").users().get(userId);
    CredentialRepresentation newCredential = new CredentialRepresentation();
    newCredential.setType(CredentialRepresentation.PASSWORD);
    newCredential.setValue("naveenm555");
    newCredential.setTemporary(false);
    userResource.resetPassword(newCredential);
    System.out.println("role created.");

This code will create new user and set role to the user. and it will allow user to login.The above code will not allow user to login after creation.

Upvotes: 1

Related Questions