認証データを取得するためのプログラマチック・ログインの開発

Java 認証・承認サービス (JAAS) ログイン・フレームワークを使用して、アプリケーションから認証データを取得できます。

このタスクについて

アプリケーションは、DefaultPrincipalMapping JAAS コンテキスト・エントリー名を使用して JAAS プログラマチック・ログインを実行し、authData エレメントに構成されたユーザー名とパスワードが入ったプライベート資格情報セット内の javax.resource.spi.security.PasswordCredential インスタンスで Subject オブジェクトを取得できます。

手順

  1. server.xml ファイルに appSecurity-2.0 フィーチャーと passwordUtilities-1.0 フィーチャーを追加します。 以下に例を示します。
    
    <featureManager>
       <feature>appSecurity-2.0</feature>
       <feature>passwordUtilities-1.0</feature>
    </featureManager>
  2. server.xml ファイルで authData エレメントを構成します。 以下に例を示します。
    
    <authData id="myAuthData" user="myUser" password="myPassword"/> <!-- password can also be encoded -->
    
    Encode the password within the configuration. You can get the encoded value by using the securityUtility encode command.
  3. アプリケーション・サーブレットまたはエンタープライズ Bean から DefaultPrincipalMapping JAAS ログイン・コンテキスト・エントリー名を使用してプログラマチック・ログインを実行し、マッピング別名を必要なものに置き換えます。 以下に例を示します。
    
    HashMap map = new HashMap();
    map.put(com.ibm.wsspi.security.auth.callback.Constants.MAPPING_ALIAS, "myAuthData"); // Replace value with your alias.
    CallbackHandler callbackHandler = new com.ibm.wsspi.security.auth.callback.WSMappingCallbackHandler(map, null);
    LoginContext loginContext = new LoginContext("DefaultPrincipalMapping", callbackHandler);
    loginContext.login();
    Subject subject = loginContext.getSubject();
    Set<javax.resource.spi.security.PasswordCredential> creds = subject.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
    PasswordCredential passwordCredential = creds.iterator().next();
    注: 簡単にするために、エラー処理は示されていません。 要求された認証別名が存在しない、またはその形式が誤りである場合、 javax.security.auth.login.LoginException が戻されます。
  4. PasswordCredentialからユーザー名とパスワードを取得します。 以下に例を示します。
    
    String userName = passwordCredential.getUserName();
    char[] password = passwordCredential.getPassword();
    // Do something with the userName and password.
  5. Java 2 セキュリティーが有効になっている場合は、アプリケーションに javax.security.auth.PrivateCredentialPermissionを付与する必要があります。 例えば、アプリケーションの META-INF/permissions.xml ファイルで、 PasswordCredential オブジェクトにアクセスするための許可を付与します。
    
    <?xml version="1.0" encoding="UTF-8"?>
    <permissions xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/permissions_7.xsd" version="7">
    
      <permission>
        <class-name>javax.security.auth.PrivateCredentialPermission</class-name>
        <name>javax.resource.spi.security.PasswordCredential * "*"</name>
        <actions>read</actions>
      </permission>
    
      <!-- Other permissions -->
    
    </permissions>

    詳しくは、 Java 2 セキュリティーを参照してください。