1. 序章

この記事では、Spring DataLDAPの統合と構成に焦点を当てます。Spring LDAPの段階的な紹介については、この記事をご覧ください。

また、SpringDataJPAガイドの概要はここにあります。

2. Maven 依存

必要なMaven依存関係を追加することから始めましょう:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-ldap</artifactId>
    <version>1.0.6.RELEASE</version>
</dependency>

spring-data-ldapの最新バージョンはここにあります。

3. ドメインエントリ

Spring LDAPプロジェクトは、 Object-Directory Mapping(ODM)を使用してLDAPエントリをJavaオブジェクトにマップする機能を提供します。

SpringLDAP記事ですでに構成されているLDAPディレクトリをマップするために使用されるエンティティを定義しましょう。

@Entry(
  base = "ou=users", 
  objectClasses = { "person", "inetOrgPerson", "top" })
public class User {
    @Id
    private Name id;
    
    private @Attribute(name = "cn") String username;
    private @Attribute(name = "sn") String password;

    // standard getters/setters
}

@Entry は、LDAPエントリのディレクトリルートにマップするエンティティを指定するために使用される @Entity (JPA / ORMの)に似ています。

Entry クラスには、エンティティDNを表すタイプjavax.naming.Nameのフィールドで宣言された@Idアノテーションが必要です。 @Attribute アノテーションは、オブジェクトクラスフィールドをエンティティフィールドにマップするために使用されます。

4. Springデータリポジトリ

Spring Data Repositoryは、さまざまな永続ストアのデータアクセスレイヤーの実装をすぐに使用できる基本的なものを提供する抽象化です。

Spring Frameworkは、データリポジトリ内の特定のクラスに対してCRUD操作の実装を内部的に提供します。 詳細については、 Spring DataJPAの記事を参照してください。

Spring Data LDAPは、LDAPディレクトリの基本的なCRUD操作を含むRepositoryインターフェースの自動実装を提供する同様の抽象化を提供します。

また、Spring Data Frameworkは、メソッド名に基づいてカスタムクエリを作成できます。

ユーザーエントリの管理に使用されるリポジトリインターフェイスを定義しましょう:

@Repository
public interface UserRepository extends LdapRepository<User> {
    User findByUsername(String username);
    User findByUsernameAndPassword(String username, String password);
    List<User> findByUsernameLikeIgnoreCase(String username);
}

ご覧のとおり、拡張してインターフェースを宣言しました LdapRepository エントリー用ユーザー。 Spring Data Frameworkは、次のような基本的なCRUDメソッドの実装を自動的に提供します。 探す() findAll() 保存()、 消去()、

また、いくつかのカスタムメソッドを宣言しました。 Spring Data Frameworkは、 Query BuilderMechanismとして知られる戦略でメソッド名をプローブすることによって実装を提供します。

5. 構成

Spring Data LDAPは、Javaベースの@ConfigurationクラスまたはXML名前空間を使用して構成できます。 Javaベースのアプローチを使用してリポジトリを構成しましょう。

@Configuration
@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**")
public class AppConfig {
}

@EnableLdapRepositories ヒントSpringは、指定されたパッケージをスキャンして、@Repository。とマークされたインターフェイスを探します。

6. スプリングブートの使用

Spring Bootプロジェクトで作業する場合、 Spring Boot Starter Data Ldap 依存関係を使用して、LdapContextSourceおよびLdapTemplateを自動的にインストルメントします。 

自動構成を有効にするには、spring-boot-starter-data-ldapスターターまたはspring-ldap-coreがpom.xmlの依存関係として定義されていることを確認する必要があります。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

LDAPに接続するには、application.propertiesで接続設定を提供する必要があります。

spring.ldap.url=ldap://localhost:18889
spring.ldap.base=dc=example,dc=com
spring.ldap.username=uid=admin,ou=system
spring.ldap.password=secret

Spring Data LDAP自動構成の詳細については、公式ドキュメントを参照してください。 Spring Bootは、 LdapAutoConfiguration を取り込み、 LdapTemplate のインストルメンテーションを処理します。これにより、必要なサービスクラスに注入できます。

@Autowired
private LdapTemplate ldapTemplate;

7. ビジネスの論理

UserRepositoryを使用してLDAPディレクトリを操作するサービスクラスを定義しましょう。

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // business methods
}

次に、一度に1つのアクションを調べ、SpringDataRepositoryを使用してこれらのアクションを簡単に実行できることを確認します。

7.1. ユーザ認証

次に、既存のユーザーを認証するための簡単なロジックを実装しましょう。

public Boolean authenticate(String u, String p) {
    return userRepository.findByUsernameAndPassword(u, p) != null;
}

7.2. ユーザーの作成

次に、新しいユーザーを作成し、パスワードのハッシュを保存しましょう。

public void create(String username, String password) {
    User newUser = new User(username,digestSHA(password));
    newUser.setId(LdapUtils.emptyLdapName());
    userRepository.save(newUser);
}

7.3. ユーザーの変更

次の方法で、既存のユーザーまたはエントリを変更できます。

public void modify(String u, String p) {
    User user = userRepository.findByUsername(u);
    user.setPassword(p);
    userRepository.save(user);
}

7.4. ユーザー検索

カスタムメソッドを使用して既存のユーザーを検索できます。

public List<String> search(String u) {
    List<User> userList = userRepository
      .findByUsernameLikeIgnoreCase(u);
    
    if (userList == null) {
        return Collections.emptyList();
    }

    return userList.stream()
      .map(User::getUsername)
      .collect(Collectors.toList());  
}

8. 実際の例

最後に、簡単な認証シナリオをすばやくテストできます。

@Test
public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() {
    Boolean isValid = userService.authenticate(USER3, USER3_PWD);
 
    assertEquals(true, isValid);
}

9. 結論

このクイックチュートリアルでは、SpringLDAPリポジトリの構成とCRUD操作の基本を示しました。

この記事で使用されている例は、GitHubにあります。