私は Jetty 埋め込み ( jetty-all-8.1.3.v20120416.jar ) を学んでおり、<security-constraint>
(HTTP BASIC) を有効にしたシンプルなサーブレットを持っています。承認を正しく確認する 2 つの単体テストは<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
==== realm.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());
}