gpt4 book ai didi

java - 在 Spring Boot 应用程序中配置 cors。 Bean CorsConfigurationSource 不起作用

转载 作者:行者123 更新时间:2023-12-02 10:02:56 25 4
gpt4 key购买 nike

所以我无法配置cors。由于错误,我的 Angular 应用程序无法发送 api 请求。我可以通过soapUI 执行请求,并且它们工作正常。但从浏览器来看有:

访问位于“http://localhost:8080/backend/api/public”的 XMLHttpRequest '来自原点'http://localhost:4200 ' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin” header 。

我正在寻找答案,它们看起来就像我的类(class)。

我正在使用 Spring Boot Web Security。

@EnableWebSecurity
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {

@Value(value = "${auth0.apiAudience}")
private String apiAudience;
@Value(value = "${auth0.issuer}")
private String issuer;


@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowCredentials(true);
configuration.addAllowedHeader("Authorization");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",configuration);
return source;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
JwtWebSecurityConfigurer
.forRS256(apiAudience, issuer)
.configure(http)
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/api/public").permitAll()
.antMatchers(HttpMethod.GET, "/api/private").authenticated()
.antMatchers(HttpMethod.GET, "/api/private-scoped").hasAnyAuthority("read:posts");
}
}

这个 bean 应该添加这个 cors header ,但它没有。也许你知道这样做更好的主意?WebSecurityConfigurerAdapter 和 WebMvcConfigurerAdapter 有什么区别?

最佳答案

根据this您还应该在 configure() 方法中添加 .cors().and()

还有其他可能的解决方案,例如通过设置特定于每个端点的 CORS 配置,如 here 所示。 .

如果您想为整个应用程序启用 CORS,第一种方法更漂亮。

WebSecurityConfigurerAdapter 和 WebMvcConfigurerAdapter 之间的区别在于,WebSecurityConfigurerAdapter 用于配置与 Web 应用程序安全相关的任何内容,例如身份验证和授权。使用 WebMvcConfigurerAdapter,您可以为 Spring MVC 自定义基于 Java 的配置。

关于java - 在 Spring Boot 应用程序中配置 cors。 Bean CorsConfigurationSource 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55500598/

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