Связывание с Active Directory
Версия: 1.26.0
Keycloak — поставщик менеджера идентификации для платформы OpenRemote. По умолчанию он использует собственную базу данных с ролями, определенными в коде для запуска.
Также можно подключить Keycloak к Active Directory и войти в систему с пользователями, пришедшими из AD. Также возможно получение групп и применение ролей Keycloak к группам.
Подробнее о Keycloak и LDAP см. в актуальной документации Keycloak.
LDAPComponentBuilder
В пакете org.openremote.manager.security вы найдете класс LDAPComponentBuilder. Этот класс — все, что вам нужно для создания org.keycloak.representations.idm.ComponentRepresentation, который будет содержать конфигурацию, позволяющую Keycloak взаимодействовать с LDAP.
Импорт пользователей
Когда пользователи из AD импортируются, существующие пользователи в Keycloak по-прежнему будут доступны. Чтобы это стало возможным, необходимо добавить ComponentRepresentation в область, используемую вашим приложением.
Пример:
RealmResource realmResource = keycloakProvider.getRealms(accessToken).realm(tenant.getRealm());
ComponentRepresentation componentRepresentation = new LDAPComponentBuilder()
.setName(LDAPComponentBuilder.ProviderId.LDAP_PROVIDER.toString())
.setProviderType(LDAPComponentBuilder.ProviderType.USER_STORAGE_PROVIDER_TYPE)
.setProviderId(LDAPComponentBuilder.ProviderId.LDAP_PROVIDER)
.setParentId(realmResource.toRepresentation().getId())
.setVendor(LDAPComponentBuilder.Vendor.AD)
.setEditMode(LDAPComponentBuilder.EditMode.READ_ONLY)
.setUserNameLDAPAttribute(LDAPComponentBuilder.LDAPConstants.UID)
.setRDNLDAPAttribute(LDAPComponentBuilder.LDAPConstants.UID)
.setUUIDLDAPAttribute(LDAPComponentBuilder.LDAPConstants.UID)
.setUserObjectClasses("inetOrgPerson,organizationalPerson")
.setConnectionUrl("ldap://ldap.forumsys.com:389")
.setUsersDn("dc=example,dc=com")
.setAuthType(LDAPComponentBuilder.AuthType.SIMPLE)
.setBindDn("cn=read-only-admin,dc=example,dc=com")
.setBindCredential("password")
.setCustomUserSearchFilter("(uid=*)")
.setSearchScope(1)
.setUseTrustStoreSPI(LDAPComponentBuilder.UseTrustStoreSpi.LDAPS_ONLY)
.setConnectionPooling(true)
.setPagination(true)
.setBatchSizeForSync(1000)
.setFullSyncPeriod(Constants.ONE_WEEK_IN_SECONDS)
.setAllowKerberosAuthentication(true)
.setKerberosRealm("EXAMPLE.COM")
.setKerberosServerPrincipal("HTTP/admin.example.com@EXAMPLE.COM")
.setKerberosKeyTabPath("/etc/krb5.keytab")
.setUseKerberosForPasswordAuthentication(false)
.setPriority(0)
.setDebug(false)
.build();
String ldapConfigId = keycloakProvider.addLDAPConfiguration(new ClientRequestInfo(null, accessToken), realmResource.toRepresentation().getRealm(), componentRepresentation);
На следующей странице](https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/) будет рассказано об используемом тестовом сервере.
Примечание
Не забудьте сопоставить файл krb5.keytab с хоста с контейнером Keycloak.
Импорт групп
Также возможно синхронизировать группы из AD с Keycloak и синхронизировать членство пользователя.
Чтобы импортировать группы, см. следующий пример:
ComponentRepresentation groupMapperComponentRepresentation = new LDAPComponentBuilder()
.setClientId(KEYCLOAK_CLIENT_ID)
.setName("GroupMapper")
.setProviderType(LDAPComponentBuilder.ProviderType.LDAP_STORAGE_MAPPER_TYPE)
.setProviderId(LDAPComponentBuilder.ProviderId.LDAP_GROUP_PROVIDER)
.setParentId(ldapConfigId)
.setMapperMode(LDAPComponentBuilder.MapperMode.IMPORT)
.setMemberShipAttributeType(LDAPComponentBuilder.MemberShipAttributeType.DN)
.setMemberShipLDAPAttribute("uniqueMember")
.setMemberShipUserLDAPAttribute(LDAPComponentBuilder.LDAPConstants.UID)
.setGroupNameLDAPAttribute("cn")
.setGroupObjectClasses("groupOfUniqueNames")
.setGroupsDn("dc=example,dc=com")
.setDropNonExistingGroupsDuringSync(false)
.setPreserveGroupInheritance(false)
.setUserRolesRetrieveStrategy(LDAPComponentBuilder.UserRolesRetrieveStrategy.LOAD_GROUPS_BY_MEMBER_ATTRIBUTE)
.build();
String mapperId = keycloakProvider.addLDAPMapper(new ClientRequestInfo(null, accessToken), realmResource.toRepresentation().getRealm(), groupMapperComponentRepresentation);
Добавление ролей Keycloak в группы
Чтобы пользователь, являющийся членом определенной группы, мог получить правильные роли от Keycloak, нам нужно предоставить группе правильные роли.
Пример:
String clientId = getClientObjectId(realmResource.clients());
//function to get the correct client idRolesResource rolesResource = realmResource.clients().get(clientId).roles();
GroupsResource groupResource = realmResource.groups();
for (GroupRepresentation groupRepresentation : groupResource.groups()) {
if (groupRepresentation.getName().equals("Scientists")) {
groupResource.group(groupRepresentation.getId()).roles().clientLevel(clientId) .add(Arrays.asList( rolesResource.get(ClientRole.READ_MAP.getValue()).toRepresentation(), rolesResource.get(ClientRole.READ_ASSETS.getValue()).toRepresentation(), rolesResource.get(ClientRole.WRITE_ASSETS.getValue()).toRepresentation(), rolesResource.get(ClientRole.WRITE_USER.getValue()).toRepresentation() ) );
}
else if (groupRepresentation.getName().equals("Mathematicians")) {
groupResource.group(groupRepresentation.getId()).roles().clientLevel(clientId) .add(Arrays.asList( rolesResource.get(ClientRole.READ_MAP.getValue()).toRepresentation(), rolesResource.get(ClientRole.READ_ASSETS.getValue()).toRepresentation() ) );
}
//etc...}
Уведомление о лицензии: атрибуция документации OpenRemote