Spring RestTemplate session

10,899

You will need to use some kind of cache to store your access token. When you'll be accessing downstream service, you take the token from cache. If cache doesn't contain token, you will authenticate and retrieve it and store to cache first.

Caching is always tricky topic, because it has to be thread-safe. I would try to avoid servlet sessions. You are consuming service, not being consumed.

There are various caching options, but as you are already using Spring, spring caching may be good fit. Take a look at this Spring Cache guide to start.

Share:
10,899
Aliyon
Author by

Aliyon

Updated on June 04, 2022

Comments

  • Aliyon
    Aliyon almost 2 years

    I'm trying to use spring rest template to do a post request to login in.

    When I receive the response in my first request i store my session id which is received via cookie. I retrieve it in a set-cookie response header which i get via:

        //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);
    

    then in every subsequent request i set the Cookie request header with the values received in the first request:

    //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);
    

    all goes well for the second request, but I can not keep the session for the others requests