在春季禁用CSRF验证

时间:2019-06-25 19:44:28

标签: java spring spring-boot spring-mvc

我想使用以下值从Ruby代码发送http请求:

http://some_domain.com?key=value&t5052&key=value&key=value

我有这个Spring配置:

@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, value = "/v1/notification")
  public ResponseEntity<String> handleNotifications(@RequestBody MultiValueMap<String, Object> keyValuePairs) {
     .....
    return new ResponseEntity<>(HttpStatus.OK);
  }

Spring转换配置:

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(converter -> converter instanceof MappingJackson2XmlHttpMessageConverter);
        converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
        converters.add(new MappingJackson2XmlHttpMessageConverter(
                ((XmlMapper) createObjectMapper(Jackson2ObjectMapperBuilder.xml()))
                        .enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)));
        converters.add(new MappingJackson2HttpMessageConverter(createObjectMapper(Jackson2ObjectMapperBuilder.json())));
    }

但是我得到了错误:

<h1>Forbidden <span>(403)</span></h1>
  <p>CSRF verification failed. Request aborted.</p>    
  <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>
  <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p>

您知道如何解决此问题吗?我可以在春季以某种方式禁用此CSRF检查吗?

1 个答案:

答案 0 :(得分:0)

您可以通过创建如下配置来禁用CSRF:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.csrf().disable();
  }
}