gpt4 book ai didi

ajax - 如何在Spring Boot中配置CORS和基本授权?

转载 作者:行者123 更新时间:2023-12-04 23:39:56 24 4
gpt4 key购买 nike

我正在尝试在已经设置了基本身份验证的Spring Boot应用程序中配置CORS。

我搜索了很多地方,包括this answer,这些地方在官方文档中都指向Filter based CORS support

到目前为止没有运气。

我的AJAX请求是通过这种方式完成的。如果是从相同来源http://localhost:8080完成的,则可以使用。

fetch('http://localhost:8080/api/lists', {
headers: {
'Authorization': 'Basic dXNlckB0ZXN0LmNvbToxMjM0NQ=='
}
}

AJAX请求是通过React应用程序的 http://localhost:3000完成的,因此我尝试了以下Spring boot CORS配置:
@Configuration
class MyConfiguration {

@Bean
public FilterRegistrationBean corsFilter()
{
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
// Maybe I can just say "*" for methods and headers
// I just copied these lists from another Dropwizard project
config.setAllowedMethods(Arrays.asList("GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD"));
config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept",
"Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods",
"Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age",
"Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Alternates",
"Content-Range", "Content-Disposition", "Content-Description"));
config.setAllowCredentials(true);

source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}

我的WebSecurityConfig:
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

http.httpBasic().and()
.authorizeRequests()
.antMatchers("/", "/index.html").permitAll()
.anyRequest().fullyAuthenticated();
}
}

来自 http://localhost:3000fetch调用在控制台中显示此401错误:

Fetch API cannot load http://localhost:8080/api/lists. Response for preflight has invalid HTTP status code 401.



enter image description here

在chrome开发工具的网络标签中,我看到以下OPTIONS请求:

enter image description here

最佳答案

我认为您需要允许OPTION请求进入您的网络安全配置。就像是:
.antMatchers(HttpMethod.OPTIONS, "/your-url").permitAll()

关于ajax - 如何在Spring Boot中配置CORS和基本授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41075850/

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