gpt4 book ai didi

java - 无法在 Spring 中配置 CSRF 以免遇到 CORS 错误

转载 作者:行者123 更新时间:2023-12-05 00:41:20 24 4
gpt4 key购买 nike

关注 Spring Boot's Issue #5834 ,为了设置正确的 CORS 并解除支持所有来源的错误,我有以下代码:

@Configuration
@EnableWebSecurity
public class SecurityAdapter extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http)
throws Exception
{
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();

authorizeRequests.antMatchers("/logon_check").permitAll();
authorizeRequests.antMatchers("/logon").permitAll();
authorizeRequests.anyRequest().authenticated();

http
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.cors()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

}


@Configuration
public class WebConfig extends WebMvcConfigurerAdapter
{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}

但是 OPTIONS 预检请求返回 403:
XMLHttpRequest cannot load http://192.168.2.10:8080/logon_check. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.10:4200' is therefore not allowed access. The response had HTTP status code 403.

这些是请求 header :
OPTIONS /logon_check HTTP/1.1
Host: 192.168.2.10:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: http://192.168.2.10:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Access-Control-Request-Headers: x-requested-with
Accept: */*
Referer: http://192.168.2.10:4200/logon
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fa;q=0.6

和响应头:
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 20
Date: Mon, 26 Jun 2017 23:56:06 GMT

有人可以帮我正确配置 Spring 以便通过所有来源吗?

最佳答案

我找到了解决问题的方法,但我不确定这种解决方法是否正确。

在跟踪 Spring 的代码几个小时后,我意识到问题出在请求中允许的 HTTP header 上。因此,更改此行可以解决问题:

configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "X-Requested-With", "X-XSRF-TOKEN"));

在上面的行中,我添加了 "X-Requested-With", "X-XSRF-TOKEN"到请求允许的 header 列表。这两个额外的标题是我需要添加的。可能还有一些其他情况/浏览器可能需要其他一些 header 。所以一般的修复可能是:
configuration.setAllowedHeaders(ImmutableList.of("*"));

但同样,我不确定这是否会带来安全风险。

关于java - 无法在 Spring 中配置 CSRF 以免遇到 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44770500/

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