【问题标题】:Spring RestTemplate sessionSpring RestTemplate 会话
【发布时间】:2023-03-28 05:42:01
【问题描述】:

我正在尝试使用 spring rest 模板发出登录请求。

当我在第一个请求中收到响应时,我会存储通过 cookie 接收的会话 ID。我在通过以下方式获得的 set-cookie 响应标头中检索它:

    //first request
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

LinkedMultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
mvm.add("LoginForm_Login", "login");
mvm.add("LoginForm_Password", "password");

ResponseEntity<String> result = restTemplate.exchange(uriDWLogin, HttpMethod.POST, requestEntity, String.class);

result.getHeaders().get("Set-Cookie").stream().forEach(System.out::println);

然后在每个后续请求中,我将 Cookie 请求标头设置为第一个请求中收到的值:

//subsequent request
RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders();
headers.set("Cookie",cookies.stream().collect(Collectors.joining(";")));
HttpEntity<String> entity = new HttpEntity<String>(headers);
RestTemplate.exchange("http://url", HttpMethod.POST, entity, String.class);

第二个请求一切顺利,但我无法为其他请求保留会话

【问题讨论】:

    标签: spring rest session cookies resttemplate


    【解决方案1】:

    您将需要使用某种缓存来存储您的访问令牌。 当您将访问下游服务时,您从缓存中获取令牌。如果缓存不包含令牌,您将首先对其进行身份验证并检索它并存储到缓存中。

    缓存总是一个棘手的话题,因为它必须是线程安全的。我会尽量避免 servlet 会话。您正在消费服务,而不是被消费。

    有多种缓存选项,但由于您已经在使用 Spring,因此 Spring 缓存可能很合适。 Take a look at this Spring Cache guide to start.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2019-06-05
      • 2016-09-07
      • 2016-01-27
      相关资源
      最近更新 更多