Search code examples
springresttemplate

Spring RestTemplate.postForEntry, returns 403 error


I want to communicate with a server in Java area by utilizing RestTemplate class. But when I access to my server with RestTemplate, it shows just 403(forbidden) error.

my controller code :

@Controller(value="homeController")
public class HomeController {

@RequestMapping(value="/test")
public @ResponseBody Map<String, String> test(@RequestParam(value="message", required=false, defaultValue="hell world") String message){

    Map<String, String> map = new HashMap<String,String>();
    map.put("greeting", message);

    return map;
}

client side's code:

@Test
public void test2(){
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("message", "test");

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

    ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
    System.out.println(response.getBody());

}

If the code works successfully, console should output "test" word.

EDIT: When I access to the controller, with my web browser, it shows json data correctly.

Now, How do I fix the code to communicate to server on POST method ? thanks


Solution

  • As you said you're using spring-security, you can simply add a request Interceptor and add authentication. Spring will create a random password if you don't set one; it will be logged in the console so you can simply copy it from there.

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(Collections.singletonList(new BasicAuthorizationInterceptor("username", "yourpassword")));
    

    Another (better) option is to configure the authentication yourself. A simple in memory auth would make

    @Configuration
    @EnableWebSecurity
    public class RestSecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().fullyAuthenticated();
            http.httpBasic();
            http.csrf().disable();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .inMemoryAuthentication()
                    .withUser("username").password("yourpassword").roles("ADMIN");
        }
    }