部署Flutter Web到Firebase Hosting后调用Heroku上Spring Boot接口报403错误求助
从日志来看,Firebase Hosting发起的OPTIONS预检请求被Heroku上的Spring Boot后端拒绝并返回403,结合本地运行正常、部署后异常的场景,问题主要集中在跨域(CORS)相关配置上,具体原因及解决方式如下:
CORS未放行Firebase Hosting域名
本地运行Flutter Web时,浏览器默认允许本地跨域调试(如localhost),但部署到Firebase后,请求的Origin变为Firebase的域名(如https://xxx.web.app)。如果Spring Boot后端的CORS配置未将该域名加入允许列表,就会拒绝OPTIONS预检请求。
解决:在Spring Boot中配置CORS时,明确添加Firebase Hosting的域名,同时确保允许OPTIONS方法。示例:// 全局CORS配置 @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 替换为你的Firebase域名 config.addAllowedOrigin("https://your-firebase-hosting-domain.web.app"); config.addAllowedHeader("*"); // 允许所有HTTP方法,包括OPTIONS config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }Spring Security拦截了OPTIONS请求
若Spring Boot应用使用Spring Security,默认配置可能会拦截OPTIONS预检请求。需要在SecurityFilterChain中放行OPTIONS请求,或确保CORS配置优先于Security生效。
解决:在Security配置中添加规则允许OPTIONS请求:@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // 优先处理CORS .cors(Customizer.withDefaults()) .authorizeHttpRequests(auth -> auth // 放行所有OPTIONS请求 .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 其他权限规则... ); return http.build(); }Firebase Hosting的重写/代理配置错误
检查firebase.json中的重写规则,如果配置了将API请求转发到Heroku,但路径匹配错误、协议不匹配,可能导致请求被篡改,触发后端403拦截。
解决:确保重写规则正确指向Heroku的API地址,示例:{ "hosting": { "rewrites": [ { "source": "/endpoint/**", "destination": "https://app.herokuapp.com/endpoint/**" } ] } }HTTPS相关的CORS配置问题
本地可能用HTTP访问后端,部署后Firebase和Heroku均使用HTTPS,若后端CORS配置仅允许HTTP的Origin,或未正确处理HTTPS请求头,也会导致403。
解决:确保CORS配置中的AllowedOrigin是HTTPS格式的Firebase域名,Heroku默认支持HTTPS,无需额外配置。
内容的提问来源于stack exchange,提问作者luckyhandler

