@Test
  @OAuth2ContextConfiguration(
      resource = OAuth2ContextConfiguration.Implicit.class,
      initialize = false)
  public void testUserMustSupplyOldPassword() throws Exception {

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    parameters.set("source", "credentials");
    parameters.set("username", joe.getUserName());
    parameters.set("password", "pas5Word");
    context.getAccessTokenRequest().putAll(parameters);

    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("Newpasswo3d");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, headers),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode());
  }
 @Override
 public void deleteApprovalsForClient(String clientId) {
   ResponseEntity<String> response =
       restTemplate.exchange(
           approvalsUrl + "?clientId=" + clientId, HttpMethod.DELETE, null, String.class);
   logger.debug("Delete approvals request for client " + clientId + " resulted in " + response);
 }
Ejemplo n.º 3
0
 public void restSend(String url) {
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.TEXT_PLAIN);
   HttpEntity<String> entity = new HttpEntity<String>("", headers);
   ResponseEntity<String> response =
       restTemplate.exchange(url, HttpMethod.GET, entity, String.class, "");
   System.out.println("Response:" + response.getBody());
 }
Ejemplo n.º 4
0
 public ResponseEntity<String> postForString(
     String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
   if (headers.getContentType() == null) {
     headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
   }
   return client.exchange(
       getUrl(path),
       HttpMethod.POST,
       new HttpEntity<MultiValueMap<String, String>>(formData, headers),
       String.class);
 }
  @Test
  public void accessServiceUsingRestTemplate() {

    // Access root resource

    URI uri = URI.create(String.format(SERVICE_URI, port));
    RequestEntity<Void> request = RequestEntity.get(uri).accept(HAL_JSON).build();
    Resource<Object> rootLinks =
        restOperations.exchange(request, new ResourceType<Object>() {}).getBody();
    Links links = new Links(rootLinks.getLinks());

    // Follow stores link

    Link storesLink = links.getLink("stores").expand();
    request = RequestEntity.get(URI.create(storesLink.getHref())).accept(HAL_JSON).build();
    Resources<Store> stores =
        restOperations.exchange(request, new ResourcesType<Store>() {}).getBody();

    stores.getContent().forEach(store -> log.info("{} - {}", store.name, store.address));
  }
 public void save(String id, Object document) {
   Assert.notNull(document, "document must not be null for save");
   HttpEntity<?> httpEntity = createHttpEntity(document);
   try {
     ResponseEntity<Map> response =
         restOperations.exchange(defaultDocumentUrl, HttpMethod.PUT, httpEntity, Map.class, id);
     // TODO update the document revision id on the object from the returned value
     // TODO better exception translation
   } catch (RestClientException e) {
     throw new UncategorizedCouchDataAccessException(e);
   }
 }
  @Test
  public void instanceJobs_emptyResponse_returnsEmptyMap() {
    when(rest.exchange(
            Matchers.any(URI.class),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(new ResponseEntity<String>("", HttpStatus.OK));

    Map<JenkinsJob, Set<Build>> jobs = defaultJenkinsClient.getInstanceJobs(URL);

    assertThat(jobs.size(), is(0));
  }
  @Override
  public Map<String, List<DescribedApproval>> getCurrentApprovalsByClientId() {
    Map<String, List<DescribedApproval>> result = new HashMap<>();
    ResponseEntity<Set<Approval>> approvalsResponse =
        restTemplate.exchange(
            approvalsUrl, HttpMethod.GET, null, new ParameterizedTypeReference<Set<Approval>>() {});
    Set<Approval> uaaapprovals = approvalsResponse.getBody();
    List<DescribedApproval> approvals = new ArrayList<>();
    for (Approval approval : uaaapprovals) {
      DescribedApproval describedApproval = new DescribedApproval(approval);
      approvals.add(describedApproval);
    }

    for (DescribedApproval approval : approvals) {
      List<DescribedApproval> clientApprovals = result.get(approval.getClientId());
      if (clientApprovals == null) {
        clientApprovals = new ArrayList<>();
        result.put(approval.getClientId(), clientApprovals);
      }

      String scope = approval.getScope();
      if (!scope.contains(".")) {
        approval.setDescription("Access your data with scope '" + scope + "'");
        clientApprovals.add(approval);
      } else {
        String resource = scope.substring(0, scope.lastIndexOf("."));
        if (Origin.UAA.equals(resource)) {
          // special case: don't need to prompt for internal uaa
          // scopes
          continue;
        }
        String access = scope.substring(scope.lastIndexOf(".") + 1);
        approval.setDescription(
            "Access your '" + resource + "' resources with scope '" + access + "'");
        clientApprovals.add(approval);
      }
    }
    for (List<DescribedApproval> approvalList : result.values()) {
      Collections.sort(
          approvalList,
          new Comparator<DescribedApproval>() {
            @Override
            public int compare(DescribedApproval o1, DescribedApproval o2) {
              return o1.getScope().compareTo(o2.getScope());
            }
          });
    }
    return result;
  }
  @Test
  @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class)
  public void testChangePasswordSameAsOldFails() {
    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("pas5Word");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, headers),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, result.getStatusCode());
  }
  // curl -v -H "Content-Type: application/json" -X PUT -H
  // "Accept: application/json" --data
  // "{\"password\":\"newpassword\",\"schemas\":[\"urn:scim:schemas:core:1.0\"]}"
  // http://localhost:8080/uaa/User/{id}/password
  @Test
  @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class)
  public void testChangePasswordSucceeds() throws Exception {
    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("Newpasswo3d");

    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<Void> result =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, headers),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.OK, result.getStatusCode());
  }
Ejemplo n.º 11
0
  @Test
  public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Void> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/authorize",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents =
        UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()).build();
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params.toSingleValueMap(), scopes, aud);
    validateToken("id_token", params.toSingleValueMap(), openid, new String[] {"cf"});
  }
  @Test
  public void verifyAuthCredentialsBySettings() throws Exception {
    // TODO: This change to clear a JAVA Warning should be correct but test fails, need to
    // investigate
    // HttpEntity<HttpHeaders> headers = new
    // HttpEntity<HttpHeaders>(defaultJenkinsClient.createHeaders("user:pass"));
    @SuppressWarnings({"rawtypes", "unchecked"})
    HttpEntity headers = new HttpEntity(defaultJenkinsClient.createHeaders("does:matter"));
    when(rest.exchange(Matchers.any(URI.class), eq(HttpMethod.GET), eq(headers), eq(String.class)))
        .thenReturn(new ResponseEntity<>("", HttpStatus.OK));

    settings.setApiKey("matter");
    settings.setUsername("does");
    defaultJenkinsClient.makeRestCall("http://jenkins.com");
    verify(rest)
        .exchange(Matchers.any(URI.class), eq(HttpMethod.GET), eq(headers), eq(String.class));
  }
Ejemplo n.º 13
0
  @Test
  public void shouldGetAllConcepts() throws Exception {
    URI url = config.toInstancePath("/concept?v=full");

    when(restOperations.exchange(
            eq(url), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class)))
        .thenReturn(getResponse(CONCEPT_LIST_RESPONSE_JSON));

    ConceptListResult result = conceptResource.getAllConcepts(config);

    verify(restOperations)
        .exchange(eq(url), eq(HttpMethod.GET), requestCaptor.capture(), eq(String.class));

    assertThat(result, equalTo(readFromFile(CONCEPT_LIST_RESPONSE_JSON, ConceptListResult.class)));
    assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForGet(config)));
    assertThat(requestCaptor.getValue().getBody(), nullValue());
  }
Ejemplo n.º 14
0
  @Test
  public void testPasswordGrant() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes()));

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", basicDigestHeaderValue);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Map> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/token",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Map.class);

    Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params, scopes, aud);
    validateToken("id_token", params, openid, new String[] {"cf"});
  }
Ejemplo n.º 15
0
  @Test
  public void shouldGetConceptById() throws Exception {
    String conceptId = "LLL";
    URI url = config.toInstancePathWithParams("/concept/{uuid}", conceptId);

    when(restOperations.exchange(
            eq(url), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class)))
        .thenReturn(getResponse(CONCEPT_CREATE_JSON));

    Concept concept = conceptResource.getConceptById(config, conceptId);

    verify(restOperations)
        .exchange(eq(url), eq(HttpMethod.GET), requestCaptor.capture(), eq(String.class));

    assertThat(concept, equalTo(readFromFile(CONCEPT_CREATE_JSON, Concept.class)));
    assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForGet(config)));
    assertThat(requestCaptor.getValue().getBody(), nullValue());
  }
Ejemplo n.º 16
0
  @Test
  public void shouldUpdateConcept() throws Exception {
    Concept concept = prepareConcept();
    URI url = config.toInstancePathWithParams("/concept/{uuid}", concept.getUuid());

    when(restOperations.exchange(
            eq(url), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class)))
        .thenReturn(getResponse(CONCEPT_RESPONSE_JSON));

    Concept updated = conceptResource.updateConcept(config, concept);

    verify(restOperations)
        .exchange(eq(url), eq(HttpMethod.POST), requestCaptor.capture(), eq(String.class));

    assertThat(updated, equalTo(concept));
    assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForPost(config)));
    assertThat(
        JsonUtils.readJson(requestCaptor.getValue().getBody(), JsonObject.class),
        equalTo(readFromFile(CONCEPT_CREATE_JSON, JsonObject.class)));
  }
Ejemplo n.º 17
0
  @Test
  public void testUserLoginViaPasswordGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.add("Authorization", ((UaaTestAccounts) testAccounts).getAuthorizationHeader("cf", ""));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "password");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity =
        restOperations.exchange(
            baseUrl + "/oauth/token",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Void.class);

    Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
  }
Ejemplo n.º 18
0
  void submitProposedConcept(final ProposedConceptPackage conceptPackage) {

    checkNotNull(submissionRestTemplate);

    //
    // Could not figure out how to get Spring to send a basic authentication request using the
    // "proper" object approach
    // see: https://github.com/johnsyweb/openmrs-cpm/wiki/Gotchas
    //

    AdministrationService service = Context.getAdministrationService();
    SubmissionDto submission = submissionDtoFactory.create(conceptPackage);

    HttpHeaders headers =
        httpHeaderFactory.create(
            service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
            service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    // headers = createHeaders(service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
    //        service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    final HttpEntity requestEntity = new HttpEntity<SubmissionDto>(submission, headers);

    final String url =
        service.getGlobalProperty(CpmConstants.SETTINGS_URL_PROPERTY)
            + "/ws/cpm/dictionarymanager/proposals";
    ResponseEntity responseEntity =
        submissionRestTemplate.exchange(
            url, HttpMethod.POST, requestEntity, SubmissionResponseDto.class);

    //		final SubmissionResponseDto result =
    // submissionRestTemplate.postForObject("http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals", submission, SubmissionResponseDto.class);
    //
    //        TODO: Find out how to determine success/failure for the submission returned by
    // dictionarymanagercontroller
    if (responseEntity == null || !responseEntity.getStatusCode().equals(HttpStatus.SC_OK)) {
      //            throw new ConceptProposalSubmissionException("Error in submitting proposed
      // concept");
      log.error("REsponseEntity status code is " + responseEntity.getStatusCode());
    }
    conceptPackage.setStatus(PackageStatus.SUBMITTED);
    Context.getService(ProposedConceptService.class).saveProposedConceptPackage(conceptPackage);
  }
  @Test
  public void instanceJobs_twoJobsTwoBuilds() throws Exception {
    when(rest.exchange(
            Matchers.any(URI.class),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(
            new ResponseEntity<String>(
                getJson("instanceJobs_twoJobsTwoBuilds.json"), HttpStatus.OK));

    Map<JenkinsJob, Set<Build>> jobs = defaultJenkinsClient.getInstanceJobs(URL);

    assertThat(jobs.size(), is(2));
    Iterator<JenkinsJob> jobIt = jobs.keySet().iterator();

    // First job
    JenkinsJob job = jobIt.next();
    assertJob(job, "job1", "http://server/job/job1/");

    Iterator<Build> buildIt = jobs.get(job).iterator();
    assertBuild(buildIt.next(), "2", "http://server/job/job1/2/");
    assertBuild(buildIt.next(), "1", "http://server/job/job1/1/");
    assertThat(buildIt.hasNext(), is(false));

    // Second job
    job = jobIt.next();
    assertJob(job, "job2", "http://server/job/job2/");

    buildIt = jobs.get(job).iterator();
    assertBuild(buildIt.next(), "2", "http://server/job/job2/2/");
    assertBuild(buildIt.next(), "1", "http://server/job/job2/1/");
    assertThat(buildIt.hasNext(), is(false));

    assertThat(jobIt.hasNext(), is(false));
  }
  @Test
  @OAuth2ContextConfiguration(
      resource = OAuth2ContextConfiguration.ClientCredentials.class,
      initialize = false)
  public void testUserAccountGetsUnlockedAfterPasswordChange() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("Authorization", testAccounts.getAuthorizationHeader("app", "appclientsecret"));

    MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();
    data.put("grant_type", Collections.singletonList("password"));
    data.put("username", Collections.singletonList(joe.getUserName()));
    data.put("password", Collections.singletonList("pas5Word"));

    ResponseEntity<Map> result =
        serverRunning.postForMap(
            serverRunning.buildUri("/oauth/token").build().toString(), data, headers);
    assertEquals(HttpStatus.OK, result.getStatusCode());

    // Lock out the account
    data.put("password", Collections.singletonList("randomPassword1"));

    for (int i = 0; i < 5; i++) {
      result =
          serverRunning.postForMap(
              serverRunning.buildUri("/oauth/token").build().toString(), data, headers);
      assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    }

    // Check that it is locked
    result =
        serverRunning.postForMap(
            serverRunning.buildUri("/oauth/token").build().toString(), data, headers);
    assertEquals("Login policy rejected authentication", result.getBody().get("error_description"));
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());

    PasswordChangeRequest change = new PasswordChangeRequest();
    change.setPassword("Newpasswo3d");

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    parameters.set("grant_type", "client_credentials");
    parameters.set("username", "admin");
    parameters.set("password", "adminsecret");
    context.getAccessTokenRequest().putAll(parameters);

    // Change the password
    HttpHeaders passwordChangeHeaders = new HttpHeaders();
    ResponseEntity<Void> passwordChangeResult =
        client.exchange(
            serverRunning.getUrl(userEndpoint) + "/{id}/password",
            HttpMethod.PUT,
            new HttpEntity<>(change, passwordChangeHeaders),
            Void.class,
            joe.getId());
    assertEquals(HttpStatus.OK, passwordChangeResult.getStatusCode());

    MultiValueMap<String, String> newData = new LinkedMultiValueMap<String, String>();
    newData.put("grant_type", Collections.singletonList("password"));
    newData.put("username", Collections.singletonList(joe.getUserName()));
    newData.put("password", Collections.singletonList("Newpasswo3d"));

    ResponseEntity<Map> updatedResult =
        serverRunning.postForMap(
            serverRunning.buildUri("/oauth/token").build().toString(), newData, headers);
    assertEquals(HttpStatus.OK, updatedResult.getStatusCode());
  }
Ejemplo n.º 21
0
 private ResponseEntity<String> exchange(
     Config config, URI url, HttpMethod method, String body, HttpHeaders headers) {
   headers.add("Authorization", "Basic " + prepareCredentials(config));
   return restOperations.exchange(url, method, new HttpEntity<>(body, headers), String.class);
 }
  @Test
  public void test_endToend() throws Exception {

    String artifacts = getJson("job-artifacts.json");
    String cucumberJson = getJson("two-features.json");

    URI lastBuildArtifactUri =
        URI.create(
            "http://server/job/job1/lastSuccessfulBuild/api/json?tree=timestamp,duration,number,fullDisplayName,building,artifacts[fileName,relativePath]");
    URI cucumberJsonUri =
        URI.create(
            "http://server/job/job1/lastSuccessfulBuild/artifact/job1/test1/report/web/cucumber.json");
    when(rest.exchange(
            eq(lastBuildArtifactUri),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(new ResponseEntity<String>(artifacts, HttpStatus.OK));
    when(rest.exchange(
            eq(cucumberJsonUri),
            eq(HttpMethod.GET),
            Matchers.any(HttpEntity.class),
            eq(String.class)))
        .thenReturn(new ResponseEntity<String>(cucumberJson, HttpStatus.OK));
    TestResult testResult = defaultJenkinsClient.getCucumberTestResult("http://server/job/job1/");
    Collection<TestCapability> capabilities = testResult.getTestCapabilities();
    assertThat(capabilities, notNullValue());

    Iterator<TestCapability> capabilityIterator = capabilities.iterator();

    TestCapability capability = capabilityIterator.next();
    List<TestSuite> suites = (List<TestSuite>) capability.getTestSuites();
    assertThat(suites, notNullValue());

    Iterator<TestSuite> suiteIt = suites.iterator();
    Iterator<TestCase> testCaseIt;
    TestSuite suite;

    suite = suiteIt.next();
    testCaseIt = suite.getTestCases().iterator();
    assertSuite(suite, "Feature:eCUKE Feature", 4, 0, 0, 4, 15019839l);

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;i-say-hi",
        "Scenario:I say hi",
        4001555l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(true));

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;you-say-hi",
        "Scenario:You say hi",
        1001212l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(true));

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;eating-cucumbers",
        "Scenario Outline:Eating Cucumbers",
        2013197l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(true));

    assertTestCase(
        testCaseIt.next(),
        "ecuke-feature;eating-cucumbers",
        "Scenario Outline:Eating Cucumbers",
        8003875l,
        TestCaseStatus.Success);
    assertThat(testCaseIt.hasNext(), is(false));
  }
Ejemplo n.º 23
0
  @Test
  public void testApprovingAnApp() throws Exception {
    ResponseEntity<SearchResults<ScimGroup>> getGroups =
        restTemplate.exchange(
            baseUrl + "/Groups?filter=displayName eq '{displayName}'",
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference<SearchResults<ScimGroup>>() {},
            "cloud_controller.read");
    ScimGroup group = getGroups.getBody().getResources().stream().findFirst().get();

    group.setDescription("Read about your clouds.");
    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", Integer.toString(group.getVersion()));
    HttpEntity request = new HttpEntity(group, headers);
    restTemplate.exchange(
        baseUrl + "/Groups/{group-id}", HttpMethod.PUT, request, Object.class, group.getId());

    ScimUser user = createUnapprovedUser();

    // Visit app
    webDriver.get(appUrl);

    // Sign in to login server
    webDriver.findElement(By.name("username")).sendKeys(user.getUserName());
    webDriver.findElement(By.name("password")).sendKeys(user.getPassword());
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();

    // Authorize the app for some scopes
    Assert.assertEquals(
        "Application Authorization", webDriver.findElement(By.cssSelector("h1")).getText());

    webDriver
        .findElement(By.xpath("//label[text()='Change your password']/preceding-sibling::input"))
        .click();
    webDriver
        .findElement(
            By.xpath(
                "//label[text()='Read user IDs and retrieve users by ID']/preceding-sibling::input"))
        .click();
    webDriver.findElement(
        By.xpath("//label[text()='Read about your clouds.']/preceding-sibling::input"));

    webDriver.findElement(By.xpath("//button[text()='Authorize']")).click();

    Assert.assertEquals("Sample Home Page", webDriver.findElement(By.cssSelector("h1")).getText());

    // View profile on the login server
    webDriver.get(baseUrl + "/profile");

    Assert.assertFalse(
        webDriver.findElement(By.xpath("//input[@value='app-password.write']")).isSelected());
    Assert.assertFalse(
        webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.read']"))
            .isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.write']"))
            .isSelected());

    // Add approvals
    webDriver.findElement(By.xpath("//input[@value='app-password.write']")).click();
    webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).click();

    webDriver.findElement(By.xpath("//button[text()='Update']")).click();

    Assert.assertTrue(
        webDriver.findElement(By.xpath("//input[@value='app-password.write']")).isSelected());
    Assert.assertTrue(
        webDriver.findElement(By.xpath("//input[@value='app-scim.userids']")).isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.read']"))
            .isSelected());
    Assert.assertTrue(
        webDriver
            .findElement(By.xpath("//input[@value='app-cloud_controller.write']"))
            .isSelected());

    // Revoke app
    webDriver.findElement(By.linkText("Revoke Access")).click();

    Assert.assertEquals(
        "Are you sure you want to revoke access to The Ultimate Oauth App?",
        webDriver.findElement(By.cssSelector(".revocation-modal p")).getText());

    // click cancel
    webDriver.findElement(By.cssSelector("#app-form .revocation-cancel")).click();

    webDriver.findElement(By.linkText("Revoke Access")).click();

    // click confirm
    webDriver.findElement(By.cssSelector("#app-form .revocation-confirm")).click();

    Assert.assertThat(
        webDriver.findElements(By.xpath("//input[@value='app-password.write']")), Matchers.empty());
  }
Ejemplo n.º 24
0
 public ResponseEntity<String> getForString(String path, HttpHeaders headers) {
   HttpEntity<Void> request = new HttpEntity<Void>((Void) null, headers);
   return client.exchange(getUrl(path), HttpMethod.GET, request, String.class);
 }
Ejemplo n.º 25
0
  private void doOpenIdHybridFlowIdTokenAndCode(
      Set<String> responseTypes, String responseTypeMatcher) throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
      String type = rTypes.next();
      responseType.append(type);
      if (rTypes.hasNext()) {
        responseType.append(" ");
      }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://*****:*****@SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse =
        restOperations.exchange(
            loginUrl + "/oauth/token",
            HttpMethod.POST,
            new HttpEntity<>(formData, tokenHeaders),
            Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
  }