...
How to Configure Security with Embedded Jetty
This example shows you how to setup web application security programmatically. Firstly, we'll look at how to do it if you use a web.xml file to declare your <security-constraint>s on urls within your webapp. Then, we'll show you how to do it in code instead, so that you don't even need to have a web.xml file.
...
We'll be using BASIC authentication for this example, but you can also set up FORM authentication in a similar way.
Using a web.xml file for security-constraints
If you're able to use a WEB-INF/web.xml file, you should configure it to use BASIC authentication, and to specify some urls that have security constraints. Here's an example:
...
| Code Block |
|---|
Server server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(8080);
server.setConnectors(new Connector[]{connector});
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath("/mywebapp");
webappcontext.setWar("./path/to/my/war/orExplodedwar");
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{webappcontext, new DefaultHandler()});
server.setHandler(handlers);
HashUserRealm myrealm = new HashUserRealm("MyRealm",System.getProperty("jetty.home)+"/etc/realm.properties");
server.setUserRealms(new UserRealm[]{myrealm});
server.start();
server.join();
|
Programmatic security constraints (no web.xml)
If you don't wish to use a web.xml file, you can specify your <security-constraint>s in code instead. Here's how we'd code the same security constraints for the web.xml file above:
| Code Block |
|---|
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();
|
Running
Assuming you deployed a webapp at the context path /mywebapp by running your application, then surfing to:
...