【问题标题】:Configuring Jersey Test Framework with Security配置 Jersey 测试框架的安全性
【发布时间】:2014-03-30 19:57:39
【问题描述】:

我正在使用 Jersey 编写一个 REST Web 服务,并且我正在尝试编写一组单元测试来使用 Jersey 测试框架来测试该服务。

但是,我使用 HTTP 身份验证和 SecurityContext 作为我的 Web 服务的一部分,我在设置 JTF 以允许我测试这些方面时遇到问题。我可以在请求中发送身份验证信息,但如何配置它以了解我希望设置的不同角色和用户?

我目前正在使用 Jetty(通过 JettyTestContainerFactory),但可以根据需要切换到不同的测试容器。

我想要实现的具体配置是两个角色和四个用户,这些用户具有这些可能角色的组合(例如,无角色、角色 a、角色 b、角色 a 和 b)。 Web 服务将处理授予对不同 URL 的访问权限,因此无需在配置中指定。

【问题讨论】:

    标签: security rest jersey jetty


    【解决方案1】:

    我通过实现自己的 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.JettyTestContainerFactoryorg.glassfish.jersey.jetty.JettyHttpContainerFactory 开始,基本上改变

    public static Server createServer(final URI uri, final SslContextFactory sslContextFactory, final JettyHttpContainer handler, final boolean start)
    

    根据需要配置安全性的嵌入式 Jetty 服务器版本的创建方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2019-01-04
      • 1970-01-01
      相关资源
      最近更新 更多