양식 로그인 처리를 위해 서블릿 필터 개발

양식 기반 로그인 메커니즘을 사용하여 로그인 화면의 룩앤필을 제어할 수 있습니다. 양식 기반 로그인에서 사용자 ID 및 비밀번호 정보를 검색하는 데 사용되는 로그인 페이지를 지정하십시오. 인증이 실패할 때 표시되는 오류 페이지를 지정할 수도 있습니다.

이 태스크 정보

인증 전후에 추가 인증 또는 추가 처리가 필요한 경우에는 서블릿 필터는 옵션입니다. 서블릿 필터는 요청 또는 응답에 포함되어 있는 정보를 변형하거나 사용하기 위해 요청 및 응답을 동적으로 방해할 수 있습니다. 하나 이상의 서블릿 필터가 서블릿 또는 서블릿 그룹에 첨부될 수 있습니다. 서블릿 필터는 또한 JSP(JavaServer Pages) 파일 및 HTML 페이지에 첨부할 수 있습니다. 모든 첨부된 서블릿 필터는 서블릿을 호출하기 전에 호출됩니다.

양식 기반 로그인 및 서블릿 필터 둘 모두 서블릿 버전 2.3 명세 준수 웹 컨테이너에 의해 지원됩니다. 양식 로그인 서블릿은 인증을 수행하고 서블릿 필터는 추가 인증, 감사 또는 정보 로깅을 수행할 수 있습니다.

서블릿 필터를 사용하여 사전 로그인 및 사후 로그인 조치를 수행하려면 이러한 필터를 양식 로그인 페이지 지원 또는 /j_security_check URL에 대해 구성하십시오. j_security_check는 사용자 이름을 포함하는 j_username 매개변수와 비밀번호를 포함하는 j_password 매개변수가 있는 양식 로그인 페이지에 의해 게시됩니다. 서블릿 필터는 추가로 인증을 수행하거나 다른 특별 요구사항을 위해 사용자 이름 매개변수 및 비밀번호 정보를 사용할 수 있습니다.

프로시저

  1. 서블릿 필터는 javax.servlet.Filter 클래스를 구현합니다. 필터 클래스에서 세 개의 메소드를 구현하십시오.
    • init(javax.servlet.FilterConfig cfg). 이 메소드는 서블릿 필터가 서비스에 배치될 때 컨테이너에 의해 한 번만 호출됩니다. 이 메소드에 전달된 FilterConfig에는 서블릿 필터의 init-parameters가 포함됩니다. 어셈블리 도구를 사용하여 구성 동안에 서블릿 필터에 init-parameters를 지정하십시오.
    • 영구 삭제. 이 메소드는 서블릿 필터가 서비스에서 벗어날 때 컨테이너에 의해 호출됩니다.
    • doFilter(ServletRequest req, ServletResponse res, FilterChain chain). 이 메소드는 서블릿을 호출하기 전에 이 필터에 맵핑하는 모든 서블릿 요청을 위해 컨테이너에 의해 호출됩니다. 이 메소드에 전달되는 FilterChain 체인은 필터 체인에서 다음 필터를 호출할 때 사용할 수 있습니다. 체인에서 마지막 필터가 chain.doFilter 메소드를 호출할 때 최초 요청된 서블릿이 실행됩니다. 그러므로 모든 필터는 필터링 후에 실행할 최초 서블릿의 chain.doFilter 메소드를 호출합니다. 추가 인증 확인이 필터 코드에서 구현되고, 결과가 실패하면, 최초 서블릿이 실행되지 않습니다. chain.doFilter 메소드가 호출되지 않고 일부 기타 오류 페이지로 경로 재지정됩니다.
  2. 서블릿이 여러 서블릿 필터로 맵핑되면 서블릿 필터는 애플리케이션의 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 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로 시작하는 행은 설명 용도를 위해서만 두 개의 행으로 분리되어 있습니다. public void doFilter(ServletRequest request 행과 그 뒤의 행은 하나의 연속하는 행입니다.
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>
An example of a revoked user list file:
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