Reputation: 1716
I want to send http request from Ruby code with these values but every time I get CSRF verification failed
:
http://some_domain.com?key=value&t5052&key=value&key=value
I have this Spring configuration:
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:
@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 'same-origin' requests.</p>
I tried to disable the CSRF filter using this Spring Security configuration code:
@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:
<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
?
Upvotes: 0
Views: 2811
Reputation: 387
Probably because of the code super.configure(http);
missing
This code works on my 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();
Upvotes: 1