我正在尝试对我的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;
}
最佳答案
安全处理程序位于资源处理程序的前面,因此在处理链中首先要查询安全处理程序。
看到:
https://github.com/eclipse/jetty.project/blob/master/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java