3 Replies Latest reply on Jan 11, 2016 5:18 AM by Bartosz Majsak

    Test Rest endpoint over https basic authentication

    klind Newbie

      Hi, how can I test rest endpoint that are using basic http authentication.

       

      I have an interface :

       

      @Path("/")
      @Produces({MediaType.APPLICATION_JSON})
      public interface RestAisUserServiceInterface {
      
         @GET
        @Path("/ais/user/{userId}")
         public Response getUser(@PathParam("userId") String userId,
         @Context UriInfo uriInfo,
         @Context HttpServletRequest servletRequest,
         @Context HttpServletResponse servletResponse) throws Exception;
      }
      

       

      And the Arquillian test

       

      @RunWith(Arquillian.class)
      public class ClientTest {
      
         @Deployment
         public static WebArchive getDeployment() {
      
        File[] files = Maven.resolver().loadPomFromFile("pom.xml")
        .importRuntimeDependencies().resolve().withTransitivity().asFile();
      
        WebArchive war = ShrinkWrap
        .create(WebArchive.class, "clienttest.war")
        .addAsLibraries(files)
        .addAsManifestResource("META-INF/beans.xml")
        .addAsResource("META-INF/persistence.xml");
        System.out.println(war.toString(true));
         return war;
        }
      
         @Test
        @RunAsClient
         public void test() {
         try {
        RestAisUserServiceInterface proxy = RestEasyClientBuilder.getProxy(RestAisUserServiceInterface.class, "https://localhost:8443/pipelineservice/v1/");
         
         // provide a httpservletcontext with cridentials ??
         
         proxy.getUser("12088", null, httpServletRequest, null);
      
        } catch (Exception e) {
        e.printStackTrace();
        }
        }
      
      }
      
        • 1. Re: Test Rest endpoint over https basic authentication
          Matous Jobanek Novice

          Hi,

           

          have you considered using Arquillian REST Client Extension arquillian/arquillian-extension-rest · GitHub  ...?

           

          Matous

          • 2. Re: Test Rest endpoint over https basic authentication
            Rafael Neves Newbie

            Hi Klind, how are your? fine?

             

            You don't need add anyway extension, just add the follow dependencies:

            <!-- Arquiilian Dependencies -->
                    <dependency>
                        <groupId>org.jboss.arquillian.junit</groupId>
                        <artifactId>arquillian-junit-container</artifactId>
                        <version>1.1.5.Final</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.jboss.arquillian.protocol</groupId>
                        <artifactId>arquillian-protocol-servlet</artifactId>
                        <version>1.1.7.Final</version>
                        <scope>test</scope>
                    </dependency>
            
            

             

            And your class like that:

            import java.net.URL;
            
            import org.codehaus.jackson.map.ObjectMapper;
            import org.jboss.arquillian.container.test.api.Deployment;
            import org.jboss.arquillian.container.test.api.OverProtocol;
            import org.jboss.arquillian.container.test.api.RunAsClient;
            import org.jboss.arquillian.junit.Arquillian;
            import org.jboss.arquillian.test.api.ArquillianResource;
            import org.jboss.shrinkwrap.api.Archive;
            import org.junit.Assert;
            import org.junit.Test;
            import org.junit.runner.RunWith;
            
            import com.company.api.commons.HTTPUtils;
            import com.company.api.models.dto.auth.UserDTO;
            
            @RunWith(Arquillian.class)
            @RunAsClient
            public class User {
            
                @Deployment(testable = true, managed = true, name = "simple")
                @OverProtocol("Servlet 2.5")
                   public static Archive<?> createTestArchive() {
                    // your deployment configuration
                }
            
                @ArquillianResource
                private URL contextPath;
            
                   private ObjectMapper mapper = new ObjectMapper();
            
                public URL getContextPath() {
                    return contextPath;
                }
            
                public void setContextPath(URL contextPath) {
                    this.contextPath = contextPath;
                }
            
                @Test
                public void testGetUser() {
                   
                    String path = "/user/?userId=1";
                    String responseBody = null;
                    UserDTO userDTO = null;
                    StringBuilder url = null;
            
                    try {
            
                        url = new StringBuilder();
                        url.append(getContextPath());
                        url.append(path);
                        responseBody = HTTPUtils.getResponseBodyAsString(url.toString());
                        if(responseBody != null){
                            userDTO = mapper.readValue(responseBody, UserDTO.class);//convert json to DTO
                        }
            
                    } catch (Throwable e) {
                        Assert.fail("Error while conversion of json object:  " + e.getMessage() + ", URL: " + url + "\n" + responseBody);
                    }
                   
                    validateUserDTO(userDTO);
                }
               
                /**
                 * Checks the DTO return by rest api.
                 * @param userDTO
                 * @author Raneves <b>raneves.mg@gmail.com<b>
                 */
                private void validateUserDTO(UserDTO userDTO) {
                   
                    Assert.assertNotNull("userDTO is null", userDTO);
                    Assert.assertNotNull("id is null", userDTO.getId());
                    Assert.assertNotNull("logAction is null", userDTO.getAction());
                    Assert.assertNotNull("clientId is null", userDTO.getClientId());
                    Assert.assertNotNull("date is null", userDTO.getDate());
                    Assert.assertNotNull("entityId is null", userDTO.getEntityId());
                    Assert.assertNotNull("entityTitle is null", userDTO.getEntityTitle());
                    Assert.assertNotNull("entityType is null", userDTO.getEntityType());
                    Assert.assertNotNull("projectId is null", userDTO.getProjectId());
                    Assert.assertNotNull("projectName is null", userDTO.getProjectName());
                    Assert.assertNotNull("userEmail is null", userDTO.getUserEmail());
                    Assert.assertNotNull("userId is null", userDTO.getUserId());
                    Assert.assertNotNull("userIP is null", userDTO.getUserIP());
                    Assert.assertNotNull("userName is null", userDTO.getUserName());
                   
                }
            }
            
            

             

            In my case I using a access_token for Spring oauth authentication, but in your case I recommend you use a simple Apache HttpClient for store your session with credentials.

            • 3. Re: Test Rest endpoint over https basic authentication
              Bartosz Majsak Master

              To make it even simpler and way more readable I strongly suggest to have a look at REST-assured. It should have all the functionalities you are looking for and will let you interact with the resource, as well as verifying the responses, a breeze.