Spring RestTemplate无法获取JSESSIONID cookie

时间:2016-04-21 19:37:43

标签: java spring spring-mvc spring-security

在我的Spring Boot / Spring Security应用程序中,我正尝试使用Spring RestTemplate登录。

这是一段代码:

final KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(new File("keystore.p12")), "changeit".toCharArray());   

final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).loadKeyMaterial(keyStore, "changeit".toCharArray()).build();   

final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);   
final HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).setRedirectStrategy(new LaxRedirectStrategy()).build();   
final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);   
final RestTemplate restTemplate = new RestTemplate(requestFactory);   

final HttpHeaders headers = new HttpHeaders();   
headers.add("Cookie", "JSESSIONID=" + loginResponse.getJsessionid());    
headers.add("X-XSRF-TOKEN", loginResponse.getCsrf());   

final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();    
body.add("username", "username");    
body.add("password", "password");    
final HttpEntity<?> requestEntity = new HttpEntity<Object>(body, headers);

final ResponseEntity<String> responseEntity = restTemplate.exchange("https://localhost:" + port + "/api/login", HttpMethod.POST, requestEntity, String.class);

这是我在responseEntity标题中收到的内容:

Server = [Apache-Coyote/1.1]
X-Content-Type-Options = [nosniff]
X-XSS-Protection = [1; mode=block]
Cache-Control = [no-cache, no-store, max-age=0, must-revalidate]
Pragma = [no-cache]
Expires = [0]
Strict-Transport-Security = [max-age=31536000 ; includeSubDomains]
Set-Cookie = [XSRF-TOKEN=cf1968b0-068b-455b-be8f-10e39e0e44a4; Path=/]
X-Application-Context = [application:0]
Content-Type = [text/plain;charset=ISO-8859-1]
Content-Length = [12]
Date = [Thu, 21 Apr 2016 19:32:34 GMT]

如您所见 - 只有XSRF-TOKEN个Cookie但没有JSESSIONID

我认为在https://localhost/api/loginhttps://localhost/api/成功进行身份验证后,可能会出现重定向问题

我做错了什么?如何接收JSESSIONID cookie?

1 个答案:

答案 0 :(得分:0)

我已使用以下StatefulRestTemplate

解决了该问题