Search code examples
androidspringcsrfhttp-status-code-403resttemplate

Android RestTemplate 403 Expected CSRF token not found


I use spring android to connect my android app to a web service made by Spring MVC and Spring security.

this is code snippet that connect to web service:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
String token  = getToken(context);
HttpHeaders httpHeader = new HttpHeaders();
httpHeader.add(RestTemplateHelper.CSRF_TOKEN_HEADER, token);
httpHeader.setContentType(MediaType.APPLICATION_JSON);
HttpEntity requestEntity = new HttpEntity(message,httpHeader);
responseEntity = rest.exchange(params[0],HttpMethod.POST, requestEntity,
GetBalanceResponse.class);

RestTemplateHelper.CSRF_TOKEN_HEADER is X-CSRF-TOKEN. This code snippet always give me error 403 with message "Expected CSRF Token not found. Has your session expired?" but if I try it from Firefox RestClient plugin also with header X-CSRF-TOKEN, it works just fine.

Some said that REST client is okay not to use CSRF, but in my case, I really need to make this work.

Please help me guys, Thanks.


Solution

  • I have found the solution of my problem. Turns out that any request sent from my android app should have Cookie header given JSESSIONID as its value. For example, "Cookie:JSESSIONID=2C01F881A33..". Spring security save token of my android app request in session, therefore my android app request must have Cookie header assigned JSESSIONID given by the server previously.