我正在尝试在我的 Jetty 服务器上提供我的一个页面的身份验证。我以编程方式完成所有操作,因此不涉及 xml。
我发现我可以使用 ConstraintSecurityHandler 保护特定的上下文。虽然这适用于我正在运行的 Servlet,但我尝试将其扩展为也适用于 ResourceHandler,但我遇到了问题。我正在尝试的代码如下所示。
如果我先放置 ResourceHandler 块,则无法弹出身份验证。如果我把 ResourceHandler 块放在 SecurityHandler 块之后,那么会弹出认证,但是认证之后,ResourceHandler 页面(/resources)没有出现,Jetty 给我一个 404。
有什么方法可以密码保护由 ResourceHandler 托管的页面以编程方式?
final static String REALM = "REALM";
.
.
.
public static void main(String[] args){
.
.
.
ResourceHandler resourceHandler = new ResourceHandler(); //set up resourceHandler to host directory of files at /resources
resourceHandler.setDirectoriesListed(true);
resourceHandler.setResourceBase("." + File.separator + "files");
ContextHandler resourceContextHandler = new ContextHandler();
resourceContextHandler.setContextPath("/resources");
resourceContextHandler.setHandler(resourceHandler);
handlers.addHandler(resourceContextHandler);
.
.
.
ConstraintSecurityHandler csh = getConstraintSecurityHandler();
ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletContextHandler.setSecurityHandler(csh);
handlers.addHandler(servletContextHandler);
.
.
.
server.setHandler(handlers);
server.start();
server.join();
}
private ConstraintSecurityHandler getConstraintSecurityHandler(){
Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, "user");
constraint.setRoles(new String[]{"user","admin"});
constraint.setAuthenticate(true);
ConstraintMapping statsConstraintMapping = new ConstraintMapping();
statsConstraintMapping.setConstraint(constraint);
statsConstraintMapping.setPathSpec("/resources"); //directory I want to protect
ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
csh.setAuthenticator(new BasicAuthenticator());
csh.setRealmName(REALM);
csh.setConstraintMappings(new ConstraintMapping[] {statsConstraintMapping});
csh.setLoginService(getHashLoginService());
return csh;
}
private HashLoginService getHashLoginService() {
HashLoginService loginServ = new HashLoginService();
loginServ.setName(REALM);
loginServ.setConfig("realm.properties"); //location of authentication file
loginServ.setRefreshInterval(1);
return loginServ;
}