List of usage examples for org.springframework.http HttpHeaders add
@Override public void add(String headerName, @Nullable String headerValue)
From source file:org.bytesoft.bytejta.supports.springcloud.web.TransactionRequestInterceptor.java
private void invokeBeforeSendRequest(HttpRequest httpRequest, String identifier) throws IOException { SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance(); TransactionBeanFactory beanFactory = beanRegistry.getBeanFactory(); TransactionManager transactionManager = beanFactory.getTransactionManager(); TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor(); TransactionImpl transaction = // (TransactionImpl) transactionManager.getTransactionQuietly(); TransactionContext transactionContext = transaction.getTransactionContext(); byte[] reqByteArray = CommonUtils.serializeObject(transactionContext); String reqTransactionStr = ByteUtils.byteArrayToString(reqByteArray); HttpHeaders reqHeaders = httpRequest.getHeaders(); reqHeaders.add(HEADER_TRANCACTION_KEY, reqTransactionStr); reqHeaders.add(HEADER_PROPAGATION_KEY, this.identifier); TransactionRequestImpl request = new TransactionRequestImpl(); request.setTransactionContext(transactionContext); RemoteCoordinator coordinator = beanRegistry.getConsumeCoordinator(identifier); request.setTargetTransactionCoordinator(coordinator); transactionInterceptor.beforeSendRequest(request); }
From source file:org.bytesoft.bytetcc.supports.springcloud.ext.CompensableRequestInterceptor.java
private void invokeBeforeSendRequest(HttpRequest httpRequest, String identifier) throws IOException { SpringCloudBeanRegistry beanRegistry = SpringCloudBeanRegistry.getInstance(); CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory(); CompensableManager compensableManager = beanFactory.getCompensableManager(); TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor(); CompensableTransactionImpl compensable = // (CompensableTransactionImpl) compensableManager.getCompensableTransactionQuietly(); TransactionContext transactionContext = compensable.getTransactionContext(); byte[] reqByteArray = CommonUtils.serializeObject(transactionContext); String reqTransactionStr = ByteUtils.byteArrayToString(reqByteArray); HttpHeaders reqHeaders = httpRequest.getHeaders(); reqHeaders.add(HEADER_TRANCACTION_KEY, reqTransactionStr); reqHeaders.add(HEADER_PROPAGATION_KEY, this.identifier); TransactionRequestImpl request = new TransactionRequestImpl(); request.setTransactionContext(transactionContext); RemoteCoordinator coordinator = beanRegistry.getConsumeCoordinator(identifier); request.setTargetTransactionCoordinator(coordinator); transactionInterceptor.beforeSendRequest(request); }
From source file:org.cloudfoundry.identity.client.UaaContextFactory.java
protected UaaContext fetchTokenFromCode(final TokenRequest request) { String clientBasicAuth = getClientBasicAuthHeader(request); RestTemplate template = new RestTemplate(); if (request.isSkipSslValidation()) { template.setRequestFactory(getNoValidatingClientHttpRequestFactory()); }//ww w .j av a 2 s. co m HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(OAuth2Utils.GRANT_TYPE, "authorization_code"); form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString()); String responseType = "token"; if (request.wantsIdToken()) { responseType += " id_token"; } form.add(OAuth2Utils.RESPONSE_TYPE, responseType); form.add("code", request.getAuthorizationCode()); ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class); return new UaaContextImpl(request, null, token.getBody()); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java
public void testAutologinFlow(String contentType, Map body) throws Exception { webDriver.get(baseUrl + "/logout.do"); HttpHeaders headers = getAppBasicAuthHttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, contentType); ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(body, headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("scope", "openid").queryParam("client_id", "app").queryParam("code", autologinCode) .build().toUriString();//from ww w.j a v a 2 s . co m webDriver.get(authorizeUrl); webDriver.get(baseUrl); Assert.assertEquals(testAccounts.getUserName(), webDriver.findElement(By.cssSelector(".header .nav")).getText()); IntegrationTestUtils.validateAccountChooserCookie(baseUrl, webDriver, IdentityZoneHolder.get()); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java
@Test public void testSimpleAutologinFlow() throws Exception { HttpHeaders headers = getAppBasicAuthHttpHeaders(); LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("username", testAccounts.getUserName()); requestBody.add("password", testAccounts.getPassword()); //generate an autologin code with our credentials ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); //start the authorization flow - this will issue a login event //by using the autologin code String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString(); //rest template that does NOT follow redirects RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory()); headers.remove("Authorization"); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET, new HttpEntity<>(new HashMap<String, String>(), headers), String.class); //we are now logged in. retrieve the JSESSIONID List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie"); int cookiesAdded = 0; headers = getAppBasicAuthHttpHeaders(); for (String cookie : cookies) { if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) { headers.add("Cookie", cookie); cookiesAdded++;//w w w. j ava2s. c om } } assertEquals(2, cookiesAdded); //if we receive a 200, then we must approve our scopes if (HttpStatus.OK == authorizeResponse.getStatusCode()) { authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("user_oauth_approval", "true") .queryParam(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody())) .build().toUriString(); authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST, new HttpEntity<>(new HashMap<String, String>(), headers), String.class); } //approval is complete, we receive a token code back assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode()); List<String> location = authorizeResponse.getHeaders().get("Location"); assertEquals(1, location.size()); String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5); //request a token using our code String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString(); MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>(); tokenParams.add("response_type", "token"); tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE); tokenParams.add("code", newCode); tokenParams.add("redirect_uri", appUrl); headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers, HttpMethod.POST, new URI(tokenUrl)); ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); //here we must reset our state. we do that by following the logout flow. headers.clear(); BasicCookieStore cookieStore = new BasicCookieStore(); ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookieStore)), String.class); setCookiesFromResponse(cookieStore, loginResponse); String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody()); requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class); cookies = loginResponse.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem(startsWith("JSESSIONID"))); assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf"))); if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) { assertThat(cookies, hasItem(startsWith("Saved-Account-"))); } assertThat(cookies, hasItem(startsWith("Current-User"))); cookieStore.clear(); setCookiesFromResponse(cookieStore, loginResponse); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookieStore)), String.class); setCookiesFromResponse(cookieStore, profilePage); String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build() .toUriString(); requestBody.clear(); requestBody.add("clientId", "app"); requestBody.add("delete", ""); requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody())); ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST, new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class); assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode()); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.OpenIdTokenGrantsIT.java
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);//from w w w. ja va 2 s. c o m if (rTypes.hasNext()) { responseType.append(" "); } } String state = new RandomValueStringGenerator().generate(); String clientId = "app"; String clientSecret = "appclientsecret"; String redirectUri = "http://localhost:8080/app/"; String uri = loginUrl + "/oauth/authorize?response_type={response_type}&" + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}"; ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers), Void.class, responseType, state, clientId, redirectUri); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { headers.add("Cookie", cookie); } } ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("username")); assertTrue(response.getBody().contains("password")); String csrf = IntegrationTestUtils.extractCookieCsrf(response.getBody()); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { headers.add("Cookie", cookie); } } MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", user.getUserName()); formData.add("password", secret); formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf); // Should be redirected to the original URL, but now authenticated result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(formData, headers), Void.class); assertEquals(HttpStatus.FOUND, result.getStatusCode()); headers.remove("Cookie"); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { headers.add("Cookie", cookie); } } location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); if (response.getStatusCode() == HttpStatus.OK) { // The grant access page should be returned assertTrue(response.getBody().contains("You can change your approval of permissions")); formData.clear(); formData.add(USER_OAUTH_APPROVAL, "true"); formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(formData, headers), Void.class); assertEquals(HttpStatus.FOUND, result.getStatusCode()); location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); } else { // Token cached so no need for second approval assertEquals(HttpStatus.FOUND, response.getStatusCode()); location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8"); } assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString())); formData.clear(); formData.add("client_id", clientId); formData.add("redirect_uri", redirectUri); formData.add("grant_type", "authorization_code"); formData.add("code", location.split("code=")[1].split("&")[0]); HttpHeaders tokenHeaders = new HttpHeaders(); String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes())); tokenHeaders.set("Authorization", basicDigestHeaderValue); @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\"")); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java
@Test public void testContentTypes() throws Exception { String loginUrl = baseUrl + "/login"; HttpHeaders jsonHeaders = new HttpHeaders(); jsonHeaders.add("Accept", "application/json"); ResponseEntity<Map> jsonResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET, new HttpEntity<>(jsonHeaders), Map.class); assertThat(jsonResponseEntity.getHeaders().get("Content-Type").get(0), containsString(APPLICATION_JSON_VALUE)); HttpHeaders htmlHeaders = new HttpHeaders(); htmlHeaders.add("Accept", "text/html"); ResponseEntity<Void> htmlResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET, new HttpEntity<>(htmlHeaders), Void.class); assertThat(htmlResponseEntity.getHeaders().get("Content-Type").get(0), containsString(TEXT_HTML_VALUE)); HttpHeaders defaultHeaders = new HttpHeaders(); defaultHeaders.add("Accept", "*/*"); ResponseEntity<Void> defaultResponseEntity = restOperations.exchange(loginUrl, HttpMethod.GET, new HttpEntity<>(defaultHeaders), Void.class); assertThat(defaultResponseEntity.getHeaders().get("Content-Type").get(0), containsString(TEXT_HTML_VALUE)); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.TestClient.java
public String getOAuthAccessToken(String baseUrl, String username, String password, String grantType, String scope) {//from www . jav a 2 s. co m HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", getBasicAuthHeaderValue(username, password)); MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>(); postParameters.add("grant_type", grantType); postParameters.add("client_id", username); if (scope != null) { postParameters.add("scope", scope); } HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>( postParameters, headers); ResponseEntity<Map> exchange = restTemplate.exchange(baseUrl + "/oauth/token", HttpMethod.POST, requestEntity, Map.class); return exchange.getBody().get("access_token").toString(); }
From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java
@Test @OAuth2ContextConfiguration(LoginClient.class) public void testLoginServerCfPasswordToken() throws Exception { ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource(); HttpHeaders headers = new HttpHeaders(); headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); params.set("client_id", resource.getClientId()); params.set("client_secret", ""); params.set("source", "login"); params.set("username", userForLoginServer.getUserName()); params.set(OriginKeys.ORIGIN, userForLoginServer.getOrigin()); params.set(UaaAuthenticationDetails.ADD_NEW, "false"); params.set("grant_type", "password"); String redirect = resource.getPreEstablishedRedirectUri(); if (redirect != null) { params.set("redirect_uri", redirect); }//ww w.j a va 2 s. c o m @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAccessTokenUri(), params, headers); assertEquals(HttpStatus.OK, response.getStatusCode()); Map results = response.getBody(); assertTrue("There should be a token: " + results, results.containsKey("access_token")); assertTrue("There should be a refresh: " + results, results.containsKey("refresh_token")); }
From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java
@Test @OAuth2ContextConfiguration(LoginClient.class) public void testLoginServerWithoutBearerToken() throws Exception { ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource(); HttpHeaders headers = new HttpHeaders(); headers.add("Accept", MediaType.APPLICATION_JSON_VALUE); headers.add("Authorization", getAuthorizationEncodedValue(resource.getClientId(), "")); params.set("client_id", resource.getClientId()); params.set("client_secret", ""); params.set("source", "login"); params.set(UaaAuthenticationDetails.ADD_NEW, "false"); params.set("grant_type", "password"); String redirect = resource.getPreEstablishedRedirectUri(); if (redirect != null) { params.set("redirect_uri", redirect); }/*from www. j av a2 s .co m*/ @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAccessTokenUri(), params, headers); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); }