Refine search
@Test public void testTokenEndpointUnauthenticated() throws Exception { ResponseEntity<String> result = http.getRestTemplate().exchange( http.getUrl("/oauth/token"), HttpMethod.GET, new HttpEntity<Void>((Void) null), String.class); // first make sure the resource is actually protected. assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); assertTrue("Wrong body: " + result.getBody(), result.getBody().toLowerCase().contains("unauthorized")); }
@RequestMapping("/") public List<Map<String,?>> home() { @SuppressWarnings("unchecked") List<Map<String,?>> result = restTemplate.getForObject(baseUrl + "/admin/beans", List.class); return result; }
@Override protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) { RequestCallback requestCallback = new XhrRequestCallback(headers); return nonNull(this.restTemplate.execute(infoUrl, HttpMethod.GET, requestCallback, textResponseExtractor)); }
private void initializeUserAccount(RestOperations client) { if (this.user == null) { UaaUser user = testAccounts.getUserWithRandomID(); @SuppressWarnings("rawtypes") ResponseEntity<Map> results = client.getForEntity(serverRunning.getUserUri() + "?filter=userName eq \"" + user.getUsername() + "\"", Map.class); assertEquals(HttpStatus.OK, results.getStatusCode()); @SuppressWarnings("unchecked") List<Map<String, ?>> resources = (List<Map<String, ?>>) results.getBody().get("resources"); Map<String, ?> map; if (!resources.isEmpty()) { map = resources.get(0); } else { map = getUserAsMap(user); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = client.postForEntity(serverRunning.getUserUri(), map, Map.class); Assert.state(response.getStatusCode() == HttpStatus.CREATED, "User account not created: status was " + response.getStatusCode()); @SuppressWarnings("unchecked") Map<String, ?> value = response.getBody(); map = value; } this.user = getUserFromMap(map); } }
private static RestOperations mockJwkSetResponse(String response) { RestOperations restOperations = mock(RestOperations.class); when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .thenReturn(new ResponseEntity<>(response, HttpStatus.OK)); return restOperations; } }
@Nullable @Override public VaultResponse read(VaultToken token) { return vaultOperations.doWithVault(restOperations -> { HttpHeaders headers = VaultHttpHeaders.from(token); try { return restOperations.exchange("sys/wrapping/unwrap", HttpMethod.POST, new HttpEntity<>(headers), VaultResponse.class).getBody(); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } if (e.getStatusCode() == HttpStatus.BAD_REQUEST && e.getResponseBodyAsString().contains("does not exist")) { return null; } throw VaultResponses.buildException(e, "sys/wrapping/unwrap"); } }); }
/** * @param headers must not be {@literal null}. * @param backend secret backend mount path, must not be {@literal null}. * @param key key within the key-value secret backend, must not be {@literal null}. * @return */ @Override public String getData(HttpHeaders headers, String backend, String key) { try { String urlTemplate = String.format("%s/v1/%s/%s", baseUrl, backend, getPath()); ResponseEntity<VaultResponse> response = rest.exchange(urlTemplate, HttpMethod.GET, new HttpEntity<>(headers), VaultResponse.class, key); HttpStatus status = response.getStatusCode(); if (status == HttpStatus.OK) { return extractDataFromBody(response.getBody()); } } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } throw e; } return null; } }
private <T extends VaultResponseSupport<?>> T writeAndReturn(String path, @Nullable Object body, Class<T> responseType) { Assert.hasText(path, "Path must not be empty"); T response = vaultOperations.doWithSession(restOperations -> { try { ResponseEntity<T> exchange = restOperations.exchange(path, HttpMethod.POST, body == null ? HttpEntity.EMPTY : new HttpEntity<>(body), responseType); return exchange.getBody(); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e, path); } }); Assert.state(response != null, "Response must not be null"); return response; }
/** * tests a happy-day flow of the native application profile. */ @Test public void testHappyDay() throws Exception { RestOperations restTemplate = serverRunning.createRestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(serverRunning.getUrl("/api/apps"), String.class); // first make sure the resource is actually protected. assertNotSame(HttpStatus.OK, response.getStatusCode()); HttpHeaders approvalHeaders = new HttpHeaders(); OAuth2AccessToken accessToken = context.getAccessToken(); approvalHeaders.set("Authorization", "bearer " + accessToken.getValue()); ResponseEntity<String> result = serverRunning.getForString("/api/apps"); assertEquals(HttpStatus.OK, result.getStatusCode()); String body = result.getBody(); assertTrue("Wrong response: " + body, body.contains("dsyerapi.cloudfoundry.com")); }
ResponseEntity<VaultResponse> entity = restOperations.exchange( "auth/{mount}/role/{role}/role-id", HttpMethod.GET, createHttpEntity(token), VaultResponse.class, options.getPath(), options.getAppRole()); return (String) entity.getBody().getRequiredData().get("role_id"); VaultResponses.getError(e.getResponseBodyAsString())), e); ResponseEntity<VaultResponse> entity = restOperations.exchange( "cubbyhole/response", HttpMethod.GET, createHttpEntity(token), VaultResponse.class); Map<String, Object> data = entity.getBody().getRequiredData(); VaultResponse response = VaultResponses.unwrap( (String) data.get("response"), VaultResponse.class); throw new VaultLoginException(String.format( "Cannot unwrap Role id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e);
@Override public Resource retrieveResource(URL url) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); ResponseEntity<String> response; try { RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, url.toURI()); response = this.restOperations.exchange(request, String.class); } catch (Exception ex) { throw new IOException(ex); } if (response.getStatusCodeValue() != 200) { throw new IOException(response.toString()); } return new Resource(response.getBody(), "UTF-8"); } }
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) { if (headers.getContentType() == null) { headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); } @SuppressWarnings("rawtypes") Map map = restTemplate.exchange(path, HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody(); @SuppressWarnings("unchecked") Map<String, Object> result = map; return result; }
@Override public List<Email> listEmails() { return Arrays .asList(getRestOperations().getForEntity(buildUriString(USER_EMAILS_PATH), Email[].class).getBody()); }
private void deleteTestClient(String clientId) throws Exception { OAuth2AccessToken token = getClientCredentialsAccessToken("clients.read,clients.write"); HttpHeaders headers = getAuthenticatedHeaders(token); ResponseEntity<Void> result = serverRunning.getRestTemplate().exchange( serverRunning.getUrl("/oauth/clients/{client}"), HttpMethod.DELETE, new HttpEntity<Void>(headers), Void.class, clientId); assertEquals(HttpStatus.OK, result.getStatusCode()); }
private boolean clientExists(RestOperations client, OAuth2ProtectedResourceDetails resource) { ResponseEntity<String> response = client.getForEntity( serverRunning.getClientsUri() + "/" + resource.getClientId(), String.class); return response != null && response.getStatusCode() == HttpStatus.OK; }
public ResponseEntity<String> postForRedirect(String path, HttpHeaders headers, MultiValueMap<String, String> params) { ResponseEntity<String> exchange = postForStatus(path, headers, params); if (exchange.getStatusCode() != HttpStatus.FOUND) { throw new IllegalStateException("Expected 302 but server returned status code " + exchange.getStatusCode()); } if (exchange.getHeaders().containsKey("Set-Cookie")) { String cookie = exchange.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } String location = exchange.getHeaders().getLocation().toString(); return client.exchange(location, HttpMethod.GET, new HttpEntity<Void>(null, headers), String.class); }
private static Map<String, Object> lookupSelf(RestOperations restOperations, VaultToken token) { try { ResponseEntity<VaultResponse> entity = restOperations.exchange( "auth/token/lookup-self", HttpMethod.GET, new HttpEntity<>( VaultHttpHeaders.from(token)), VaultResponse.class); Assert.state(entity.getBody() != null && entity.getBody().getData() != null, "Token response is null"); return entity.getBody().getData(); } catch (HttpStatusCodeException e) { throw new VaultTokenLookupException(String.format( "Token self-lookup failed: %s %s", e.getRawStatusCode(), VaultResponses.getError(e.getResponseBodyAsString()))); } catch (RestClientException e) { throw new VaultTokenLookupException("Token self-lookup failed", e); } }
@Override public VaultHealth doWithRestOperations(RestOperations restOperations) { try { ResponseEntity<VaultHealthImpl> healthResponse = restOperations.exchange( "sys/health", HttpMethod.GET, null, VaultHealthImpl.class); return healthResponse.getBody(); } catch (HttpStatusCodeException responseError) { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(responseError.getResponseBodyAsString(), VaultHealthImpl.class); } catch (Exception jsonError) { throw responseError; } } } }
@Nullable @Override public Policy getPolicy(String name) throws VaultException { Assert.hasText(name, "Name must not be null or empty"); return vaultOperations.doWithSession(restOperations -> { ResponseEntity<VaultResponse> response; try { response = restOperations.getForEntity("sys/policy/{name}", VaultResponse.class, name); } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { return null; } throw e; } String rules = (String) response.getBody().getRequiredData().get("rules"); if (StringUtils.isEmpty(rules)) { return Policy.empty(); } if (rules.trim().startsWith("{")) { return VaultResponses.unwrap(rules, Policy.class); } throw new UnsupportedOperationException("Cannot parse policy in HCL format"); }); }
@Override public InputStream getCrl(Encoding encoding) throws VaultException { Assert.notNull(encoding, "Encoding must not be null"); return vaultOperations.doWithSession(restOperations -> { String requestPath = encoding == Encoding.DER ? "{path}/crl" : "{path}/crl/pem"; try { ResponseEntity<byte[]> response = restOperations.getForEntity( requestPath, byte[].class, path); return new ByteArrayInputStream(response.getBody()); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } }); }