【问题标题】:Disable CSRF verification in Spring在 Spring 中禁用 CSRF 验证
【发布时间】:2019-11-07 16:54:16
【问题描述】:

我想用这些值从 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 检查吗?

【问题讨论】:

标签: java spring spring-boot spring-mvc


【解决方案1】:

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

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

【讨论】:

  • 我有这个配置http.csrf().disable().authorizeRequests().antMatchers("/notification").permitAll().anyRequest().permitAll();,但它不起作用。
  • 上面有@EnableWebSecurity 或@EnableGlobalMethodSecurity(prePostEnabled = true) 注释吗?
猜你喜欢
  • 2015-03-18
  • 2019-06-21
  • 2023-03-19
  • 2013-05-03
  • 1970-01-01
  • 2020-05-04
  • 2017-03-12
  • 2011-05-03
  • 1970-01-01
相关资源
最近更新 更多