目前我尝试使用Keycloak API和Java客户端。目前,我很难以编程方式将角色分配给群组。不幸的是,文档目前还不是很精细。
这是我的示例代码:
@Test
public void testPushGroupWithRealmRoles() throws IOException {
GroupRepresentation group = new GroupRepresentation();
group.setName("JUnit Test Group realm roles");
String editRoleName = "junit_edit";
String deleteRoleName = "junit_delete";
RoleRepresentation editRole = getRealmRole(editRoleName);
if (editRole == null) {
editRole = new RoleRepresentation(editRoleName, "is allowed to edit", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(editRole);
}
RoleRepresentation deleteRole = getRealmRole(deleteRoleName);
if (deleteRole == null) {
deleteRole = new RoleRepresentation(deleteRoleName, "is allowed to delete", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(deleteRole);
}
group.setRealmRoles(Arrays.asList(editRole.getName(), deleteRole.getName()));
GroupResource existingGroup = getGroupRepresentation(group.getName());
if(existingGroup != null){
existingGroup.update(group);
} else{
getKeycloak().realm(clientConfig.getRealm()).groups().add(group);
}
}
如果不存在,则创建组,如果角色不存在,则创建角色
group.setRealmRoles(Arrays.asList(editRole.getName(), deleteRole.getName()));
需要在字符串列表中作为参数给出什么?角色的名字?角色的技术ID? (两者都不适合我)。
感谢任何帮助!
更新 感谢ravthiru,我能够解决我的问题。工作代码是这样的:
@Test
public void testPushGroupWithRealmRoles() throws IOException {
/*
ensure the roles exist
*/
String editRoleName = "junit_edit";
String deleteRoleName = "junit_delete";
RoleRepresentation editRole = getRealmRole(editRoleName);
if (editRole == null) {
editRole = new RoleRepresentation(editRoleName, "is allowed to edit", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(editRole);
}
RoleRepresentation deleteRole = getRealmRole(deleteRoleName);
if (deleteRole == null) {
deleteRole = new RoleRepresentation(deleteRoleName, "is allowed to delete", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(deleteRole);
}
/*
ensure the group exists
*/
GroupRepresentation group = new GroupRepresentation();
group.setName("JUnit Test Group realm roles");
GroupResource existingGroup = getGroupResource(group.getName());
if (existingGroup != null) {
existingGroup.update(group);
} else {
getKeycloak().realm(clientConfig.getRealm()).groups().add(group);
}
/*
assign roles to group
*/
existingGroup.roles().realmLevel().add(Arrays.asList(editRole, deleteRole));
}
答案 0 :(得分:5)
如果您已创建角色,则可以使用以下代码将角色与组关联。
RoleRepresentation grouprole = realm.roles().get("grouprole").toRepresentation();
List<RoleRepresentation> roles = new LinkedList<>();
roles.add(grouprole);
realm.groups().group(myGroup.getId()).roles().realmLevel().add(roles);
此处“grouprole”角色与“myGroup”组相关联