简体   繁体   English

无法在Spring Boot中禁用CSRF安全性

[英]Cannot disable CSRF security in Spring Boot

I want to send http request from Ruby code with these values but every time I get CSRF verification failed : 我想使用这些值从Ruby代码发送http请求,但是每次我获得CSRF verification failed

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

I have this Spring configuration: 我有这个Spring配置:

Endpoint: 终点:

@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 convert config: Spring转换配置:

@SpringBootApplication(scanBasePackages = { "org.rest.api.*", "org.plugin.service", "org.plugin.transactions.factory" })
@EntityScan("org.plugin.entity")
@EnableJpaRepositories("org.plugin.service")
@EnableScheduling
public class Application extends SpringBootServletInitializer implements WebMvcConfigurer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @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())));
    }

    private ObjectMapper createObjectMapper(Jackson2ObjectMapperBuilder builder) {
        builder.indentOutput(true);
        builder.modules(new JaxbAnnotationModule());
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.defaultUseWrapper(false);
        return builder.build();
    }
}

But I get error: 但是我得到了错误:

<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>

I tried to disable the CSRF filter using this Spring Security configuration code: 我尝试使用以下Spring Security配置代码禁用CSRF过滤器:

@Configuration
@EnableWebSecurity
@Import(value = { Application.class, ContextDatasource.class })
@ComponentScan(basePackages = { "org.rest.api.server.*" })
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthEntryPoint authenticationEntryPoint;

    @Autowired
    MerchantAuthService myUserDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(myUserDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/notification").permitAll().anyRequest().permitAll();
        http.httpBasic().authenticationEntryPoint(authenticationEntryPoint);
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

POM Configuration: POM配置:

<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.6.RELEASE</version>
</parent>
....
<dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-web</artifactId>
</dependency>

Do you know how I can fix this issue? 您知道如何解决此问题吗? Can I somehow disable this CSRF check in Spring only for /notification ? 我可以以某种方式仅在/notification禁用此CSRF检查吗?

Probably because of the code super.configure(http); 可能是因为代码super.configure(http); missing 失踪

This code works on my PC: 该代码可在我的PC上使用:

@EnableWebSecurity
@Configuration
class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService myUserDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                UserDetails userDetails = null;
                try {
                    userDetails = new User("admin", "admin", getAuthorities());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return userDetails;
            }

            private Collection<GrantedAuthority> getAuthorities() {
                List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
                authList.add(new SimpleGrantedAuthority("ROLE_USER"));
                authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                return authList;
            }

        };
    }

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

and I can find login page will add the tag 我可以找到登录页面将添加标签

<input name="_csrf" type="hidden" value="7a943334-47ed-4e81-b59b-445b70db080b">

if I commented http.csrf().disable(); 如果我评论了http.csrf()。disable();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM