gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:44:33 26 4
gpt4 key购买 nike

我想从 Ruby 代码发送具有这些值的 http 请求,但每次我收到 CSRF 验证失败:

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 转换配置:

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

但是我收到错误:

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

我尝试使用以下 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 配置:

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

你知道我该如何解决这个问题吗?我可以以某种方式在 Spring 中仅针对 /notification 禁用此 CSRF 检查吗?

最佳答案

可能是因为代码super.configure(http);失踪

此代码适用于我的电脑:

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

我可以发现登录页面将添加标签

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

如果我评论http.csrf().disable();

关于java - 无法在 Spring Boot 中禁用 CSRF 安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com