I have set up my spring server to respond to a POST request containing a Message object as:
@RequestMapping(value = "/signup", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody Message signUp(@RequestBody Message message) {
logger.info("Accessing protected resource");
return new Message(100, "Congratulations!", "You have signed up. msg:"+message.toString());
}
The Android client is set up to send the request as:
@Override
protected Message doInBackground(Void... params) {
// TODO Auto-generated method stub
final String url = "http://10.0.2.2:8080/signup";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Message> requestEntity = new HttpEntity<Message>(signupmsg, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
try {
// Make the network request
Log.d(TAG, url);
ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Message.class);
return response.getBody();
} catch (HttpClientErrorException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return new Message(0, e.getStatusText(), e.getLocalizedMessage());
} catch (ResourceAccessException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return new Message(0, e.getClass().getSimpleName(), e.getLocalizedMessage());
}
}
However the server always returns a 403 Forbidden error. I expect it to return another Message object The Message object is custom defined in a separate class. However, if I send a GET request with no encapsulated object, it works. I am new to Spring. What am I missing here?
Update: I diagnosed this problem, and it is happening when I enable spring web security. With no security, the POST request succeeds. I tried disabling the security in the configuration but it still does not work. (GET requests work fine though.) I currently have the following in my WebSecurityConfiguration.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.inMemoryAuthentication()
.withUser("roy")
.password("spring")
.roles("USER");
// @formatter:on
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().permitAll()
.and()
.httpBasic().disable();
// @formatter:on
}
I enabled web security by adding the following to my build.gradle
compile("org.springframework.boot:spring-boot-starter-security")
I tried sending a POST request using browser using a REST client and it gives the error: HTTP Status 403 - Expected CSRF token not found. Has your session expired?
Fixed it temporarily by using .csrf().disable()
What is the best way to solve this?