|
| 1 | +package org.javaee7.servlet.security; |
| 2 | + |
| 3 | +import com.meterware.httpunit.AuthorizationRequiredException; |
| 4 | +import com.meterware.httpunit.GetMethodWebRequest; |
| 5 | +import com.meterware.httpunit.WebConversation; |
| 6 | +import com.meterware.httpunit.WebResponse; |
| 7 | +import java.io.File; |
| 8 | +import java.net.URL; |
| 9 | +import org.jboss.arquillian.container.test.api.Deployment; |
| 10 | +import org.jboss.arquillian.junit.Arquillian; |
| 11 | +import org.jboss.arquillian.test.api.ArquillianResource; |
| 12 | +import org.jboss.shrinkwrap.api.ShrinkWrap; |
| 13 | +import org.jboss.shrinkwrap.api.spec.WebArchive; |
| 14 | +import org.junit.Test; |
| 15 | +import static org.junit.Assert.*; |
| 16 | +import org.junit.runner.RunWith; |
| 17 | + |
| 18 | +/** |
| 19 | + * @author Arun Gupta |
| 20 | + */ |
| 21 | +@RunWith(Arquillian.class) |
| 22 | +public class SecureServletTest { |
| 23 | + |
| 24 | + private static final String WEBAPP_SRC = "src/main/webapp"; |
| 25 | + |
| 26 | + @ArquillianResource |
| 27 | + private URL base; |
| 28 | + |
| 29 | + @Deployment(testable = false) |
| 30 | + public static WebArchive createDeployment() { |
| 31 | + WebArchive war = ShrinkWrap.create(WebArchive.class). |
| 32 | + addClass(SecureServlet.class). |
| 33 | + addAsWebInfResource((new File(WEBAPP_SRC + "/WEB-INF", "web.xml"))); |
| 34 | + return war; |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void testSecureServletWithCorrectCredentials() throws Exception { |
| 39 | + WebConversation conv = new WebConversation(); |
| 40 | + conv.setAuthentication("file", "u1", "p1"); |
| 41 | + GetMethodWebRequest getRequest = new GetMethodWebRequest(base + "/SecureServlet"); |
| 42 | + WebResponse getResponse = conv.getResponse(getRequest); |
| 43 | + assertTrue(getResponse.getText().contains("<title>Servlet Security - Basic Auth with File-base Realm</title>")); |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + public void testSecureServletWithIncorrectCredentials() throws Exception { |
| 48 | + WebConversation conv = new WebConversation(); |
| 49 | + conv.setAuthentication("file", "u", "p1"); |
| 50 | + GetMethodWebRequest getRequest = new GetMethodWebRequest(base + "/SecureServlet"); |
| 51 | + try { |
| 52 | + conv.getResponse(getRequest); |
| 53 | + } catch (AuthorizationRequiredException e) { |
| 54 | + assertNotNull(e); |
| 55 | + return; |
| 56 | + } |
| 57 | + fail("/SecureServlet could be accessed without proper security credentials"); |
| 58 | + } |
| 59 | +} |
0 commit comments