当前位置: 首页 > article >正文

SpringBoot3中跨域问题解决

问题

SpringBoot3 中处理跨域请求

异常

浏览器在 localhost:3000 地址请求后端 http://127.0.0.1:8080 时, 报错提示 CORS 问题.
默认使用 Get 请求正常, 其他会提示.
使用 SpringBoot 3.4.2 版本配合 SpringSecurity 配置

Access to fetch at 'http://127.0.0.1:8080/todo-task/list' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决

需要在 Spring Security 配置以下内容…


/**
 * Spring Security 配置
 *
 * @author Jion
 */
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    private final CustomAuthenticationEntryPoint unauthorizedHandler;


    /**
     * 配置过滤器链
     *
     * @param http 请求
     * @return 过滤器链
     * @throws Exception 抛出异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		// 一些其他配置等...
		
        // 跨域请求
        http.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfigurationSource()));
        return http.build();
    }


    /**
     * 跨域配置, 仅在开发环境有必要.
     * 如果是发布之后, 桌面应用不会产生跨域问题.
     */
    @Bean
    public UrlBasedCorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许本地域名访问
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000", "http://127.0.0.1:3000"));
        // 允许被本地域名访问
        configuration.setAllowedOriginPatterns(Arrays.asList("http://localhost:3000/**", "http://127.0.0.1:3000/**"));
        // 允许所有请求方法
        configuration.setAllowedMethods(List.of("*"));
        // 允许所有请求头
        configuration.setAllowedHeaders(List.of("*"));
        // 允许所有响应头
        configuration.setExposedHeaders(List.of("*"));
        // 允许携带凭证
        configuration.setAllowCredentials(true);
        // 跨域请求配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 匹配所有请求路径
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}


http://www.kler.cn/a/556979.html

相关文章:

  • 新一代MPP数据库:StarRocks
  • Redis7——基础篇(五)
  • 大数据开发治理平台~DataWorks(词汇梳理)
  • SmartX 超融合硬盘健康检测机制升级(附故障模拟性能实测)
  • Python 学习之旅:高级阶段(十一)数据库操作 Redis
  • Docker 与 Nginx:容器化 Web 服务器
  • 欢乐力扣:赎金信
  • R 语言科研绘图第 27 期 --- 密度图-分组
  • 【DeepSeek】-macOS本地终端部署后运行DeepSeek如何分析图片
  • 【UCB CS 61B SP24】Lecture 7 - Lists 4: Arrays and Lists学习笔记
  • ios UICollectionView使用自定义UICollectionViewCell
  • Centos虚拟机扩展磁盘空间
  • 短视频平台“封号圈”乱象猖獗,IP查询技术助力整治
  • 反射机制详解
  • 基于 Spring Boot 的社区居民健康管理系统部署说明书
  • 代码审计入门学习之sql注入
  • 海外企业真的需要跨境专线网络吗?
  • Nmap:网络扫描与安全评估的多功能工具
  • tailwindcss 前端 css 框架 无需写css 快速构建页面
  • 用 UniApp 打造新颖美观的弹出框