簡體   English   中英

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

[英]Configuring cors in spring boot application. Bean CorsConfigurationSource doesnt work

所以我不能配置cors。 由於錯誤,我的 angular 應用程序無法發送 api 請求。 我可以通過soapUI 執行請求,並且它們工作正常。 但是從瀏覽器有:

從源“ http://localhost:4200 ”訪問“ http://localhost:8080/backend/api/public ”的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”標頭在請求的資源上。

我一直在尋找答案,它們看起來像我的班級。

我正在使用 Spring Boot Web 安全。

@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 頭,但它沒有。 也許你知道這樣做的更好主意? WebSecurityConfigurerAdapter 和 WebMvcConfigurerAdapter 有什么區別?

根據這個你應該增加.cors().and()在您的configure()方法為好。

還有其他可行的解決方案,例如,通過所看到的CORS配置特定的設置,以每個端點這里

如果你想為你的整個應用程序啟用 CORS,第一種方法更漂亮。

WebSecurityConfigurerAdapter 和 WebMvcConfigurerAdapter 之間的區別在於,WebSecurityConfigurerAdapter 用於配置與 Web 應用程序安全相關的任何內容,例如身份驗證和授權。 使用 WebMvcConfigurerAdapter,您可以為 Spring MVC 自定義基於 Java 的配置。

我遇到了同樣的問題,無法使 CorsConfigurationSource bean 工作。 所以我嘗試了不同的方法。 我沒有使用 CorsConfigurationSource bean 配置。 相反,我使用了 cors 注冊表替代或全局 CORS 配置。

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("http://localhost:4200")
            .allowCredentials(true);
    }
}

從 AuthConfig 類中刪除 CorsConfigurationSource 配置 bean。 我從https://www.baeldung.com/spring-cors得到了這段代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM