本文共 2117 字,大约阅读时间需要 7 分钟。
跨域请求配置问题解决方案
在前后端交互时,跨域请求是一个常见的问题。特别是在使用Spring Security进行身份验证时,如果没有正确配置CORS,可能会导致preflight请求被拒绝。以下是针对这种问题的详细解决方案。
当我尝试从一个域名(http://localhost:8080)向另一个域名(http://localhost:8081)发起HTTP请求时,浏览器报错:
Access to XMLHttpRequest at 'http://localhost:8081/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
这意味着浏览器在处理preflight请求时遇到了问题,可能是由于CORS配置不正确。
在我之前的尝试中,我配置了CORS,但问题依旧存在。于是我仔细检查了配置,并发现以下问题:
http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();,但似乎还不够。通过查看Spring Security官方文档,我找到了正确的CORS配置方法。以下是详细的解决步骤:
CorsConfigurer来配置CORS。以下是配置代码:@Beanpublic CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("*"); configuration.addAllowedMethod("*"); configuration.addAllowedHeader("*"); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source;} configure方法中,启用CORS支持:@Overrideprotected void configure(HttpSecurity http) { http.cors(Customizer.withDefaults()); // 其他安全配置} http.authorizeRequests() .requestMatchers(CorsUtils::isPreFlightRequest) .permitAll();
allowedOrigin:设置*允许所有域名,http://localhost:8080在开发环境中常用。allowedMethods:设置*允许所有方法,包括GET、POST等。allowedHeaders:设置*允许所有头,包括Access-Control-Allow-Origin等。allowCredentials:设置true允许cookie、token等凭证。在完成配置后,进行以下测试:
通过以上配置,前后端的跨域请求问题应该能够顺利解决。遇到具体问题时,可以参考Spring Security官方文档或相关博客,找到更详细的解决方案。
转载地址:http://iteo.baihongyu.com/