フォーム・ログイン処理のためのサーブレット・フィルターの開発

フォーム・ベースのログイン・メカニズムを使用すると、 ログイン画面のルック・アンド・フィールを制御できます。 フォーム・ベースのログインでは、ユーザー ID およびパスワード情報 を取り出すために使用するログイン・ページを指定します。認証が失敗したときに 表示されるエラー・ペ ージを指定することもできます。

このタスクについて

認証の前後に追加の認証 または追加処理が必要な場合は、オプションでサーブレット・フィルターを使用できます。サーブレット・フィルターは、 要求と応答を動的にインターセプトし、その要求または応答に含まれている 情報を変換または使用することができます。 1 つ以上のサーブレット・フィルターを、サーブレットまたはサーブレットの グループに付加することができます。 サーブレット・フィルターは、JavaServer Pages (JSP) ファイルおよび HTML ページに付加することもできます。付加されたすべてのサーブレット・フィルターは、 サーブレットを起動する前に呼び出されます。

フォーム・ベースのログインとサーブレット・フィルターは両方とも、サーブレット・バージョン 2.3 仕様に準拠するすべての Web コンテナーによってサポートされます。フォーム・ログイン・サーブレットは認証を実行し、サーブレット・フィルターは、 追加の認証または情報の監査やロギングを実行します。

サーブレット・フィルターを使用して事前ログインおよび事後ログインのアクション を実行するには、これらのフィルターを、フォーム・ログイン・ページ・サポート 用または /j_security_check URL 用のいずれかに構成してください。j_security_check は、ユーザー名を含む j_username パラメーター、 およびパスワードを含む j_password パラメーターを指定した、 フォーム・ログイン・ページでポストされます。サーブレット・フィルターは、 ユーザー名パラメーターおよびパスワード情報を使用して、さらに多くの認証またはその他の特別なニーズ を実行できます。

手順

  1. サーブレット・フィルターは javax.servlet.Filter クラスを実装します。フィルター・クラスで 3 つのメソッドを実装します。
    • init(javax.servlet.FilterConfig cfg)。 このメソッドは、コンテナーによって、 サーブレット・フィルターがサービス内に入れられるときに一度呼び出されます。 このメソッドに渡される FilterConfig には、サーブレット・フィルターの 初期パラメーターが含まれています。サーブレット・フィルターの初期パラメーターは、 構成する際にアセンブリー・ツールを使用して指定してください。
    • destroy。このメソッドは、コンテナーによって、サーブレット・フィルターがサービスから取り出されるときに呼び出されます。
    • doFilter(ServletRequest 要求、ServletResponse 応答、FilterChain チェーン)。 このメソッドは、サーブレットを呼び出す前に、このフィルターにマップされる 各サーブレット要求ごとに、コンテナーによって呼び出されます。このメソッドに渡される FilterChain チェーンを使用して、 フィルターのチェーン内の次のフィルターを呼び出すことができます。 要求された元のサーブレットは、チェーン内の最後のフィルター が chain.doFilter メソッドを呼び出すときに実行されます。 したがって、元のサーブレットをフィルター操作の後に 実行するために、すべてのフィルターが chain.doFilter メソッドを呼び出します。 追加の認証検査がフィルター・コードに実装されており、 その結果が失敗した場合は、元のサーブレットは実行されません。 chain.doFilter メソッドは呼び出されず、その他のなんらかのエラー・ページ にリダイレクトすることができます。
  2. 1 つのサーブレットが多数のサーブレット・フィルターにマップしている場合、サーブレット・フィルターは、アプリケーションの web.xml デプロイメント記述子にリストされている順に呼び出されます。サーブレット・フィルター・クラス・ファイル は、アプリケーションの WEB-INF/classes ディレクトリーに置いてください。

以下にサーブレット・フィルターの例を示します。

このログイン・フィルターは、ログイン前およびログイン後のアクションを実行するために /j_security_check URL にマップすることができます。

import javax.servlet.*;
     public class LoginFilter implements Filter {
     protected FilterConfig filterConfig;
     // Called once when this filter is instantiated. 
     // If mapped to j_security_check, called
     // very first time j_security_check is invoked.
     public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        }
     public void destroy() {
        this.filterConfig = null;
        }
      // Called for every request that is mapped to this filter. 
     // If mapped to j_security_check,
     // called for every  j_security_check action
     public void doFilter(ServletRequest request, 
     ServletResponse response, FilterChain chain) 
         throws java.io.IOException, ServletException   {
         // perform pre-login action here
         chain.doFilter(request, response);
         // calls the next filter in chain.
         // j_security_check if this filter is 
         // mapped to j_security_check.
        // perform post-login action here.
                 }
       }
サーブレット・フィルターを使用して、フォーム・ログイン中にログイン前後処理を実行する

この例では、Servlet フィルターが、 フォーム・ログイン時に、ログイン前、およびログイン後の処理を実行する 方法の 1 つを示します。

Servlet filter source code: LoginFilter.java
/**
 * A servlet filter example: This example filters j_security_check and
 * performs pre-login action to determine if the user trying to log in
 * is in the revoked list. If the user is on the revoked list, an error is
 * sent back to the browser.
 *
 * This filter reads the revoked list file name from the FilterConfig 
 * passed in the init() method. It reads the revoked user list file and
 * creates a revokedUsers list.
 * 
 * When the doFilter method is called, the user logging in is checked 
 * to make sure that the user is not on the revoked Users list.
 *
 */

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LoginFilter implements Filter {

   protected FilterConfig filterConfig;

   java.util.List revokeList; 
   

   /**
    * init() : init() method called when the filter is instantiated.
    * This filter is instantiated the first time j_security_check is 
    * invoked for the application (When a protected servlet in the 
    * application is accessed).
    */
   public void init(FilterConfig filterConfig) throws ServletException {
      this.filterConfig = filterConfig;

      // read revoked user list
      revokeList = new java.util.ArrayList(); 
      readConfig();
   }


   /**
    * destroy() : destroy() method called when the filter is taken 
    * out of service.
    */
   public void destroy() {
      this.filterConfig = null;
      revokeList = null;
   }

   /**
    * doFilter() : doFilter() method called before the servlet to 
    * which this filter is mapped is invoked. Since this filter is  
    * mapped to j_security_check,this method is called before 
    * j_security_check action is posted.
    */
   public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain) throws java.io.IOException, ServletException {


      HttpServletRequest req = (HttpServletRequest)request;
      HttpServletResponse res = (HttpServletResponse)response;

      // pre login action
      
      // get username 
      String username = req.getParameter("j_username");

      // if user is in revoked list send error
      if ( revokeList.contains(username) ) {
      res.sendError(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
      return;
      }
      
      // call next filter in the chain : let j_security_check authenticate 
      // user
      chain.doFilter(request, response);

      // post login action

   }

   /**
    * readConfig() : Reads revoked user list file and creates a revoked 
    * user list.
    */
   private void readConfig() {
      if ( filterConfig != null ) {

         // get the revoked user list file and open it.
         BufferedReader in;
         try {
               String filename = filterConfig.getInitParameter("RevokedUsers");
               in = new BufferedReader( new FileReader(filename));
         } catch ( FileNotFoundException fnfe) {
               return;
         }
	
         // read all the revoked users and add to revokeList. 
         String userName;
         try {
               while ( (userName = in.readLine()) != null ) 
                   revokeList.add(userName);
         } catch (IOException ioe) {
         }

      }
  
   }

   
}
重要: 上記のコード・サンプルでは、public void doFilter(ServletRequest request で始まる行は、 表示上の理由で 2 行に分割されています。 public void doFilter(ServletRequest request で始まる行およびそれに続く行は、連続した 1 つの行です。
j_security_check URL に構成およびマップされた LoginFilter フィルターを示す web.xml ファイルの例:
<filter id="Filter_1">
    <filter-name>LoginFilter</filter-name>
	   	   <filter-class>LoginFilter</filter-class>
	        	        <description>Performs pre-login and post-login operation</description>
			 <init-param>
			 			 <param-name>RevokedUsers</param-name>
			 			 <param-value>c:¥WebSphere¥AppServer¥installedApps¥
                            <app-name>¥revokedUsers.lst</param-value>
				</init-param>
</filter-id>

<filter-mapping>
	<filter-name>LoginFilter</filter-name>
	    	    <url-pattern>/j_security_check</url-pattern>
</filter-mapping>
取り消されたユーザー・リスト・ファイルの例を以下に示します。
user1
cn=user1,o=ibm,c=us
user99
cn=user99,o=ibm,c=us

トピックのタイプを示すアイコン タスク・トピック



タイム・スタンプ・アイコン 最終更新: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=tsec_servlet
ファイル名:tsec_servlet.html