如何在没有XML的Jetty中为ResourceHandler提供安全认证?

时间:2012-07-13 20:09:37

标签: security jetty constraints password-protection

我正在尝试在我的Jetty服务器上提供我的某个页面的身份验证。我是以编程方式完成的,所以没有涉及xml。

我发现我可以使用ConstraintSecurityHandler来保护特定的上下文。虽然这对我正在运行的Servlet工作正常,但我也尝试将其扩展为ResourceHandler,我遇到了问题。我正在尝试的代码如下所示。

如果我先放置ResourceHandler块,则无法弹出身份验证。 如果我将SecurityHandler块放在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;
}

1 个答案:

答案 0 :(得分:4)

安全处理程序位于资源处理程序之前,因此在处理链中首先查阅安全处理程序。

见:

https://github.com/eclipse/jetty.project/blob/master/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java