我通过实现自己的 Jetty Test 容器来实现这一点,类似于 Jersey 提供的容器。我们使用嵌入式 Jetty 在开发中正常测试我们的应用程序,并通过基于该嵌入式 Jetty 创建我们自己的测试容器来加载我们的 Web 应用程序,就像它由 Java 主进程启动一样。
我们使用在 jetty-env.xml 文件中配置的自定义 Jetty 安全处理程序,嵌入式 Jetty 使用该文件来配置安全性。
<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>
Jetty env 文件是由嵌入式 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.");
}
该 xml 中引用的 users.properties 文件是一个简单的用户到角色映射,例如
USERNAME=PASSWORD,ROLE_NAME1,ROLE_NAME2
根据您配置 Jetty 安全性的方式,这可能适合您,也可能不适合您。您也可以通过编程方式进行配置,有很多嵌入式 Jetty here 的示例。 SecuredHelloHandler.java 示例对您来说可能是一个好的开始。
对于测试容器,您基本上可以从复制org.glassfish.jersey.test.jetty.JettyTestContainerFactory 和org.glassfish.jersey.jetty.JettyHttpContainerFactory 开始,基本上改变
public static Server createServer(final URI uri, final SslContextFactory sslContextFactory, final JettyHttpContainer handler, final boolean start)
根据需要配置安全性的嵌入式 Jetty 服务器版本的创建方法。