我想在我的Jetty服務器上提供我的一個頁面的身份驗證。我以編程方式完成所有工作,所以沒有涉及到xml。如何在沒有XML的Jetty中爲ResourceHandler提供安全認證?
我發現我可以通過使用ConstraintSecurityHandler來保護特定的上下文。雖然這對我正在運行的Servlet正常工作,但我試圖將它擴展到ResourceHandler,並且遇到了問題。我正在嘗試的代碼如下。
如果我先放置ResourceHandler塊,那麼身份驗證將無法彈出。 如果我放在SecurityHandler塊後ResourceHandler塊,則認證彈出,但身份驗證之後,ResourceHandler頁面(/資源)沒有出現,和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;
}
爲了澄清,安全處理程序必須指向Web應用程序的處理程序,因此它確保了Web應用程序。我有一個處理程序列表(ContextHandlerCollection),只是將安全處理程序添加到此列表中 - 這並不起作用。 – davidfrancis 2015-06-17 10:24:34
你也可以使用jetty.xml文件來說明這是如何實現的嗎? – Sohan 2015-12-24 09:31:56