安卓App一站式抓包与漏洞测试:Charles+BurpSuite+Postern实战指南
2026/7/1 18:36:06
作为编程新手,在前后端联调时经常会遇到如下报错:
Access to XMLHttpRequest at 'http://localhost:8120/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.本文将从问题本质、产生原因和解决方案三个层面,用通俗易懂的方式讲解这个错误。
浏览器遵循「同源策略」:只有当请求的协议、域名和端口完全一致时,才允许前端获取后端数据,否则就是跨域请求。
以报错为例:
| 报错片段 | 解释 |
|---|---|
| Access to XMLHttpRequest at ‘http://localhost:8120/login’ | 前端尝试请求后端接口 |
| from origin ‘http://localhost:3000’ | 前端源为3000端口 |
| blocked by CORS policy | 被浏览器跨域规则拦截 |
| No ‘Access-Control-Allow-Origin’ header | 后端响应缺少关键跨域头信息 |
总结:浏览器出于安全考虑阻止了跨域请求,因为后端未明确授权前端访问。
浏览器设计「同源策略」是为了安全(如防止恶意网站窃取登录信息),但给开发带来不便。
跨域请求流程:
@Configuration@EnableWebSecuritypublicclassSecurityConfig{@BeanpublicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{http.cors(cors->cors.configurationSource(corsConfigurationSource())).csrf(csrf->csrf.disable()).authorizeHttpRequests(auth->auth.requestMatchers(HttpMethod.OPTIONS,"/**").permitAll().requestMatchers("/api/**").permitAll().anyRequest().permitAll()).sessionManagement(session->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).formLogin(form->form.disable());returnhttp.build();}@BeanpublicCorsConfigurationSourcecorsConfigurationSource(){CorsConfigurationconfig=newCorsConfiguration();config.addAllowedOrigin("http://localhost:3000");config.setAllowCredentials(true);config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS"));config.setAllowedHeaders(Arrays.asList("*"));config.setMaxAge(3600L);UrlBasedCorsConfigurationSourcesource=newUrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**",config);returnsource;}}当后端暂时无法修改时,前端可通过设置代理使请求"伪装"为同源请求。
exportdefaultdefineConfig({server:{proxy:{'/api':{target:'http://localhost:8120',changeOrigin:true}}}});{"proxy":"http://localhost:8120"}检查:
requestMatchers(HttpMethod.OPTIONS, "/**").permitAll().sessionCreationPolicy(SessionCreationPolicy.STATELESS)使用浏览器开发者工具:
Access-Control-Allow-Origin: http://localhost:3000核心问题:浏览器因安全机制拦截跨域请求,需后端明确授权
解决方案:
注意:确保启动类扫描到SecurityConfig所在包
上面的启动类要指定扫描你的SecurityConfig类所在包"com.exam.config"
-默认扫描行为 :未显式指定@ComponentScan时,SpringBoot会扫描 启动类所在包及其所有子包 (即 com.exam 及其所有子包,包括 com.exam.config )。-显式扫描覆盖 :添加显式@ComponentScan(basePackages=...)后,默认扫描范围被完全覆盖,Spring仅扫描 指定的包路径 ,不会自动包含启动类所在包的子包。-配置失效原因 :-移除"com.exam.config"后,您自定义的SecurityConfig.java (位于 com.exam.config 包)未被Spring容器加载-Spring使用了默认的WebSecurityConfiguration和 defaultSecurityFilterChain-默认配置没有您自定义的CORS设置(CorsConfigurationSource),导致跨域请求被拦截-默认配置启用了表单登录,将POST请求重定向至GET/login,进一步导致跨域请求失败