Password protect app in jetty

jetty

I am testing a webapp (.war) running in Jetty 7. For demo purposes I want to run this on a public URL, however I would like not to have the whole world (if they happen to come across the URL) be able to see it.

Is there a way to make Jetty require a basic-auth type of authentication when accessing the webapp (without modifying anything inside the war, i.e. no edits on the web.xml file)? Or if not the webapp, then any part of what Jetty provides at port 8080?

Best Answer

Take a look at the full example here:

The above is Web archive link, original link is now unavailable:

Programmatic configuration example from the above:

import org.mortbay.jetty.security.*;

Server server = new Server();

Connector connector = new SelectChannelConnector();
connector.setPort(8080);
server.setConnectors(new Connector[]{connector});

Constraint constraint = new Constraint();
constraint.setName(Constraint.__BASIC_AUTH);;
constraint.setRoles(new String[]{"user","admin","moderator"});
constraint.setAuthenticate(true);

ConstraintMapping cm = new ConstraintMapping();
cm.setConstraint(constraint);
cm.setPathSpec("/*");

SecurityHandler sh = new SecurityHandler();
sh.setUserRealm(new HashUserRealm("MyRealm",System.getProperty("jetty.home")+"/etc/realm.properties"));
sh.setConstraintMappings(new ConstraintMapping[]{cm});

WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath("/mywebapp");
webappcontext.setWar("./path/to/my/war/orExplodedwar");
webappcontext.addHandler(sh);

HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{webappcontext, new DefaultHandler()});

server.setHandler(handlers);
server.start();
server.join();