第96章 LDAP


LDAP コンポーネント

ldap コンポーネントを使用すると、フィルターを使用してメッセージペイロードとして LDAP サーバーで検索を実行できます。このコンポーネントは、標準の JNDI (javax.naming パッケージ)を使用してサーバーにアクセスします。

URI 形式

ldap:ldapServerBean[?options]
Copy to Clipboard Toggle word wrap
URI の ldapServerBean 部分は、レジストリーの DirContext Bean を参照します。LDAP コンポーネントはプロデューサーエンドポイントのみをサポートします。つまり、ldap URI はルートの開始時に from に表示されることができません。
URI にクエリーオプションは ?option=value&option=value&.. の形式で追加できます。

オプション

Expand
名前 デフォルト値 説明
base ou=system 検索用のベース DN。
scope subtree ベース DN から始まるエントリーのツリーを詳しく検索する方法を指定します。値は、オブジェクト1 次、または サブツリー にすることができます。
pageSize ページングは使用されません。 LDAP モジュールはページングを使用してすべての結果を取得します(ほとんどの LDAP サーバーは 1 つのクエリーで複数のエントリーを取得しようとすると例外を出力します)。これを使用できるようにするには、LdapContext ( DirContextのサブクラス)を ldapServerBean として渡す必要があります(そうでない場合は例外が発生します)。
returnedAttributes LDAP サーバー(すべてまたはなし)に依存します。 結果の各エントリーに設定する必要がある属性のコンマ区切りリスト

結果

結果は、ArrayList<javax.naming.directory.SearchResult > オブジェクトとして Out ボディーで返されます。

DirContext

URI ldap:ldapserver は、ldapserver という ID を持つ Spring Bean を参照します。ldapserver Bean は以下のように定義できます。
<bean id="ldapserver" class="javax.naming.directory.InitialDirContext" scope="prototype">
  <constructor-arg>
    <props>
      <prop key="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</prop>
      <prop key="java.naming.provider.url">ldap://localhost:10389</prop>
      <prop key="java.naming.security.authentication">none</prop>
    </props>
  </constructor-arg>
</bean>
Copy to Clipboard Toggle word wrap
上記の例では、匿名でローカルでホストされる LDAP サーバーに接続する通常の Sun ベースの LDAP DirContext を宣言します。
注記
DirContext オブジェクトは、コントラクトによる同時実行をサポートする必要は ありません。そのため、ディレクトリーコンテキストは Bean 定義で設定 scope="prototype" で宣言されるか、コンテキストが同時実行をサポートすることが重要です。Spring フレームワークでは、プロトタイプ スコープオブジェクトは検索時に毎回インスタンス化されます。

サンプル

上記の Spring 設定から、以下のコードサンプルは LDAP 要求を送信し、メンバーのグループを検索します。次に、Common Name が応答から抽出されます。
ProducerTemplate<Exchange> template = exchange
  .getContext().createProducerTemplate();

Collection<?> results = (Collection<?>) (template
  .sendBody(
    "ldap:ldapserver?base=ou=mygroup,ou=groups,ou=system",
    "(member=uid=huntc,ou=users,ou=system)"));

if (results.size() > 0) {
  // Extract what we need from the device's profile

  Iterator<?> resultIter = results.iterator();
  SearchResult searchResult = (SearchResult) resultIter
      .next();
  Attributes attributes = searchResult
      .getAttributes();
  Attribute deviceCNAttr = attributes.get("cn");
  String deviceCN = (String) deviceCNAttr.get();

  ...
Copy to Clipboard Toggle word wrap
特定のフィルターが必要ない場合(たとえば、単一のエントリーのみ)。ワイルドカードフィルター式を指定します。たとえば、LDAP エントリーに Common Name がある場合は、以下のようなフィルター式を使用します。
(cn=*)
Copy to Clipboard Toggle word wrap

認証情報を使用したバインディング

Camel エンドユーザーは、クレデンシャルを使用して ldap サーバーにバインドするのに使用したこのサンプルコードをしました。
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.setProperty(Context.PROVIDER_URL, "ldap://localhost:389");
props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url");
props.setProperty(Context.REFERRAL, "ignore");
props.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
props.setProperty(Context.SECURITY_PRINCIPAL, "cn=Manager");
props.setProperty(Context.SECURITY_CREDENTIALS, "secret");

SimpleRegistry reg = new SimpleRegistry();
reg.put("myldap", new InitialLdapContext(props, null));

CamelContext context = new DefaultCamelContext(reg);
context.addRoutes(
    new RouteBuilder() {
        public void configure() throws Exception { 
            from("direct:start").to("ldap:myldap?base=ou=test");
        }
    }
);
context.start();

ProducerTemplate template = context.createProducerTemplate();

Endpoint endpoint = context.getEndpoint("direct:start");
Exchange exchange = endpoint.createExchange();
exchange.getIn().setBody("(uid=test)");
Exchange out = template.send(endpoint, exchange);

Collection<SearchResult> data = out.getOut().getBody(Collection.class);
assert data != null;
assert !data.isEmpty();

System.out.println(out.getOut().getBody());

context.stop();
Copy to Clipboard Toggle word wrap

SSL の設定

以下の例のように、InitialDirContext Bean でカスタムソケットファクトリーを作成し、参照することのみが必要になります。
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
                 http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">


    <sslContextParameters xmlns="http://camel.apache.org/schema/blueprint"
                          id="sslContextParameters">
        <keyManagers
                keyPassword="{{keystore.pwd}}">
            <keyStore
                    resource="{{keystore.url}}"
                    password="{{keystore.pwd}}"/>
        </keyManagers>
    </sslContextParameters>

    <bean id="customSocketFactory" class="zotix.co.util.CustomSocketFactory">
        <argument ref="sslContextParameters" />
    </bean>
    <bean id="ldapserver" class="javax.naming.directory.InitialDirContext" scope="prototype">
        <argument>
            <props>
                <prop key="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory"/>
                <prop key="java.naming.provider.url" value="ldaps://lab.zotix.co:636"/>
                <prop key="java.naming.security.protocol" value="ssl"/>
                <prop key="java.naming.security.authentication" value="simple" />
                <prop key="java.naming.security.principal" value="cn=Manager,dc=example,dc=com"/>
                <prop key="java.naming.security.credentials" value="passw0rd"/>
                <prop key="java.naming.ldap.factory.socket"
                      value="zotix.co.util.CustomSocketFactory"/>
            </props>
        </argument>
    </bean>
</blueprint>
Copy to Clipboard Toggle word wrap
CustomSocketFactory クラスは以下のように実装されます。
import org.apache.camel.util.jsse.SSLContextParameters;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyStore;

/**
 * The CustomSocketFactory. Loads the KeyStore and creates an instance of SSLSocketFactory
 */
public class CustomSocketFactory extends SSLSocketFactory {

    private static SSLSocketFactory socketFactory;

    /**
     * Called by the getDefault() method.
     */
    public CustomSocketFactory() {

    }

    /**
     * Called by Blueprint DI to initialise an instance of SocketFactory
     *
     * @param sslContextParameters
     */
    public CustomSocketFactory(SSLContextParameters sslContextParameters) {
        try {
            KeyStore keyStore = sslContextParameters.getKeyManagers().getKeyStore().createKeyStore();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(keyStore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tmf.getTrustManagers(), null);
            socketFactory = ctx.getSocketFactory();
        } catch (Exception ex) {
            ex.printStackTrace(System.err);  /* handle exception */
        }
    }

    /**
     * Getter for the SocketFactory
     *
     * @return
     */
    public static SocketFactory getDefault() {
        return new CustomSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return socketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return socketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
        return socketFactory.createSocket(socket, string, i, bln);
    }

    @Override
    public Socket createSocket(String string, int i) throws IOException {
        return socketFactory.createSocket(string, i);
    }

    @Override
    public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException {
        return socketFactory.createSocket(string, i, ia, i1);
    }

    @Override
    public Socket createSocket(InetAddress ia, int i) throws IOException {
        return socketFactory.createSocket(ia, i);
    }

    @Override
    public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
        return socketFactory.createSocket(ia, i, ia1, i1);
    }
}
Copy to Clipboard Toggle word wrap
トップに戻る
Red Hat logoGithubredditYoutubeTwitter

詳細情報

試用、購入および販売

コミュニティー

Red Hat ドキュメントについて

Red Hat をお使いのお客様が、信頼できるコンテンツが含まれている製品やサービスを活用することで、イノベーションを行い、目標を達成できるようにします。 最新の更新を見る.

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

Theme

© 2025 Red Hat