2012-05-25 74 views
1

靜態網頁我可以這樣來配置靜態內容:基本HTTP驗證在碼頭8

ContextHandler staticContext = new ContextHandler(); 
    staticContext.setContextPath("/"); 
    staticContext.setResourceBase("."); 
    staticContext.setClassLoader(Thread.currentThread().getContextClassLoader()); 

    ResourceHandler resourceHandler = new ResourceHandler(); 
    resourceHandler.setDirectoriesListed(true); 
    resourceHandler.setWelcomeFiles(new String[]{"index.html"}); 

    resourceHandler.setResourceBase(webDir); 

    staticContext.setHandler(resourceHandler); 

現在我想設置基本HTTP認證爲我所有的靜態文件。我怎樣才能做到這一點?

PS。我使用的是嵌入式碼頭全無的web.xml

回答

3

覆蓋ResourceHandler#handle()的東西,如:

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { 
    String authHeader = request.getHeader("Authorization"); 

    if (authHeader != null && authHeader.startsWith("Basic ")) { 
     String[] up = parseBasic(authHeader.substring(authHeader.indexOf(" ") + 1)); 
     String username = up[0]; 
     String password = up[1]; 
     if (authenticateUser(username, password)) { 
      super.handle(target, baseRequest, request, response); 
      return; 
     } 
    } 

    response.setHeader("WWW-Authenticate", "BASIC realm=\"SecureFiles\""); 
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please provide username and password"); 
} 

private boolean authenticateUser(String username, String password) { 
    // Perform authentication here 
    return true; // .. if authentication is successful 
} 

private String[] parseBasic(String enc) { 
    byte[] bytes = Base64.decodeBase64(enc.getBytes()); 
    String s = new String(bytes); 
    int pos = s.indexOf(":"); 
    if(pos >= 0) 
     return new String[] { s.substring(0, pos), s.substring(pos + 1) }; 
    else 
     return new String[] { s, null }; 
} 

以上Base64.decodeBase64是Apache共享編解碼器。當然,您可以找到一個爲您執行基本身份驗證的庫,但您可以在此查看封面下發生的情況。另一種方法是使用基本身份驗證過濾器並將其安裝到您的上下文中。