【问题标题】:SpringBoot + REST, Cross-Origin Request Blocked: Reason: CORS request did not succeedSpring Boot + REST,Cross-Origin Request Blocked: 原因:CORS 请求没有成功
【发布时间】:2020-10-29 21:13:56
【问题描述】:

我在使用 CORS 时遇到了问题,但仅限于某些版本的 Firefox 和 Safari:跨域请求被阻止:同源策略不允许在...处读取远程资源(原因:CORS 请求未成功)。在 Chrome 中,它适用于所有测试机器。这是我的配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@EnableAutoConfiguration
public class ApplicationConfig extends WebSecurityConfigurerAdapter {
    private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
            new AntPathRequestMatcher("/some_public_urls")
    );
    private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);

    TokenAuthenticationProvider provider;

    public ApplicationConfig(final TokenAuthenticationProvider provider) {
        super();
        this.provider = requireNonNull(provider);
    }

    @Autowired
    private Environment env;

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(provider);
    }

    @Override
    public void configure(final WebSecurity web) {
        web.ignoring().requestMatchers(PUBLIC_URLS);
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
                .headers()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(STATELESS)
                .and()
                .exceptionHandling()
                .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
                .and()
                .authenticationProvider(provider)
                .addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .requestMatchers(PROTECTED_URLS)
                .authenticated()
                .and()
                .cors()
                .and()
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
        final TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(successHandler());
        return filter;
    }

    @Bean
    SimpleUrlAuthenticationSuccessHandler successHandler() {
        final SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
        successHandler.setRedirectStrategy((httpServletRequest, httpServletResponse, s) -> {
            // No redirect is required
        });
        return successHandler;
    }

    /**
     * Disable Spring boot automatic filter registration.
     */
    @Bean
    FilterRegistrationBean disableAutoRegistration(final TokenAuthenticationFilter filter) {
        final FilterRegistrationBean registration = new FilterRegistrationBean(filter);
        registration.setEnabled(false);
        return registration;
    }

    @Bean
    AuthenticationEntryPoint forbiddenEntryPoint() {
        return new HttpStatusEntryPoint(FORBIDDEN);
    }
}

每个 RestController 都标注有:

@RestController
@CrossOrigin

【问题讨论】:

  • 好的,那么失败的请求是什么,响应是什么,完整的错误消息是什么?

标签: java spring spring-boot


【解决方案1】:

我猜你是在一些旧的浏览器上进行测试,但它不起作用。

Here 是浏览器中对 CORS 的支持。请检查一下。

截至 2014 年年中,大约 83% 的浏览器具有完整的 支持 CORS,另有 6% 部分支持。

如果是这种情况,您可以尝试其他一些技术,例如 JSON-P 或使用 Proxy Server 在旧版浏览器中进行跨域请求。

【讨论】:

    【解决方案2】:

    好的, 原来,这是证书问题。我们有一个证书包(通配符证书),但顺序错误。有些浏览器可以处理这个问题,有些版本的 Firefox 会阻止它。

    【讨论】:

      猜你喜欢
      • 2021-08-08
      • 2016-04-11
      • 1970-01-01
      • 2021-07-02
      • 2017-10-19
      • 2020-06-11
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多