我有这样配置的静态内容:
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 身份验证。我该怎么做?
附言。我在 web.xml 中使用嵌入式 Jetty
最佳答案
用类似的东西覆盖 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 Commons Codec。当然,您可以找到一个为您执行 Basic Auth 的库,但在这里您可以看到幕后发生的事情。另一种方法可能是使用基本身份验证过滤器并将其安装到您的上下文中。
关于java - Jetty 8 中静态页面的基本 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10750978/