1

我正在学习 Jetty 嵌入式( jetty-all-8.1.3.v20120416.jar ),并且我有一个简单的 servlet,我已经启用了<security-constraint>(HTTP BASIC)。我的两个单元测试检查授权是否正确通过和失败(一个使用我的 realm.properties 中的用户名和密码发出请求,另一个尝试在不进行身份验证的情况下连接)<role-name>users</role-name>,但在<role-name>*</role-name>. JUnit 对不正确结果的总结(参见下面的方法定义):

testPingServletAuthenticated(): Expected: OK, Actual: Forbidden
testPingServletUnauthenticated(): Passed

文件片段包含在下面('====' 将它们分开)。我希望这是足够的信息。提前致谢!——马特

==== web.xml ====

servlet-mapping
  servlet-name: hello-servlet
  url-pattern: /hello-web-xml

security-constraint
  url-pattern: /*
  auth-constraint:
    role-name: users

login-config
  auth-method: BASIC
  realm-name: test security realm

security-role
  role-name: users

==== 领域.properties ====

theuser:password,users

==== HelloServlet.java ====

very simple doGet()

==== JettySetupTest.java ====

public static void startJettyServer() throws Exception {
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setDescriptor("out/artifacts/diy_embedded_testing_war_exploded/WEB-INF/web.xml");
    webAppContext.setResourceBase("out/artifacts/diy_embedded_testing_war_exploded/");
    webAppContext.setContextPath(CONTEXT_PATH);
    webAppContext.setParentLoaderPriority(true);    // Q: needed?

    LoginService loginService = new HashLoginService("test security realm", "test/embed/realm.properties"); // NB: must match realm name in web.xml's <login-config><realm-name>
    webAppContext.getSecurityHandler().setLoginService(loginService);

    SERVER = new Server(PORT);
    SERVER.setHandler(webAppContext);
    SERVER.start();
}


@Test
public void testPingServletAuthenticated() throws IOException {
    Client client = Client.create();
    WebResource webResource = client.resource(BASE_URL + "/hello-web-xml");     // http://localhost:8080/app/hello-web-xml
    webResource.addFilter(new HTTPBasicAuthFilter("theuser", "password"));
    ClientResponse clientResponse = webResource
            .accept(MediaType.TEXT_PLAIN)
            .get(ClientResponse.class);     // @GET
    assertEquals(ClientResponse.Status.OK, clientResponse.getClientResponseStatus());
    assertEquals(HelloServlet.GREETING + "\n", clientResponse.getEntity(String.class));
}


@Test
public void testPingServletUnauthenticated() throws IOException {
    Client client = Client.create();
    WebResource webResource = client.resource(BASE_URL + "/hello-web-xml");     // http://localhost:8080/app/hello-web-xml
    ClientResponse clientResponse = webResource
            .accept(MediaType.TEXT_PLAIN)
            .get(ClientResponse.class);     // @GET
    assertEquals(ClientResponse.Status.UNAUTHORIZED, clientResponse.getClientResponseStatus());
} 
4

1 回答 1

2

我想到了。<role-name>我对如何在 web.xml 中使用有一个基本的误解。我想如果我在中使用“*” <security-constraint><auth-constraint><role-name>,那么它也应该在中列出<security-role><role-name>。但是,我发现后者应该列出应用程序中使用的实际角色,在我的例子中是“用户”。

于 2012-06-21T23:21:54.730 回答