I have done this by implementing my own Jetty Test container similar to the one provided by Jersey. We use an embedded Jetty for testing our application in development normally and by creating our own test container based on that embedded Jetty it loads our web application as it would if it was started by a Java main process.
We use a custom Jetty Security Handler configured in a jetty-env.xml file which the embedded Jetty uses to configure the security.
<Set name="securityHandler">
<New class="com.example.DevelopmentSecurityHandler">
<Set name="loginService">
<New class="com.example.DevelopmentLoginService">
<Set name="name">LocalRealm</Set>
<Set name="config">src/main/webapp/WEB-INF/users.properties</Set>
<Call name="start" />
</New>
</Set>
<Set name="authenticator">
<New class="com.example.DevelopmentAuthenticator"></New>
</Set>
<Set name="checkWelcomeFiles">true</Set>
</New>
</Set>
That Jetty env file is loaded by embedded Jetty:
XmlConfiguration configuration = null;
if (jettyEnvFile.exists()) {
try {
configuration = new XmlConfiguration(jettyEnvFile.toURI().toURL());
} catch (Exception e) {
throw new ProcessingException(String.format("Exception loading jetty config from %s", jettyEnvFile));
}
} else {
LOG.warn("No jetty-env.xml found.");
}
The users.properties file referenced in that xml is a simple user to role mapping e.g.
USERNAME=PASSWORD,ROLE_NAME1,ROLE_NAME2
Depending how you configure your Jetty security this may or may not work for you. You can also configure this programmatically, there's lots of examples of embedded Jetty here. The SecuredHelloHandler.java example there could be a good start for you.
For the test container you can basically start by copying org.glassfish.jersey.test.jetty.JettyTestContainerFactory
and org.glassfish.jersey.jetty.JettyHttpContainerFactory
essentially changing the
public static Server createServer(final URI uri, final SslContextFactory sslContextFactory, final JettyHttpContainer handler, final boolean start)
method to create your version of an embedded Jetty server with security configured however you require.