面试题:Spring Boot 如何处理跨域请求(CORS)?

在 Spring Boot 中处理跨域请求(CORS,Cross-Origin Resource Sharing)是一个常见的需求,尤其是在前后端分离的架构中。Spring Boot 提供了多种方式来处理跨域请求,以下是常用的几种方法:


1. 使用 @CrossOrigin 注解

@CrossOrigin 注解可以直接应用于控制器类或方法上,用于允许特定的跨域请求。

在方法级别使用:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @CrossOrigin(origins = "https://example.com") // 允许来自 https://example.com 的跨域请求
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

在类级别使用:

@CrossOrigin(origins = "https://example.com") // 允许来自 https://example.com 的跨域请求
@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }

    @GetMapping("/greet")
    public String greet() {
        return "Greetings!";
    }
}

2. 全局配置 CORS

如果你希望为整个应用配置跨域规则,可以通过实现 WebMvcConfigurer 接口并重写 addCorsMappings 方法。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许所有路径
                .allowedOrigins("https://example.com") // 允许的源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的 HTTP 方法
                .allowedHeaders("*") // 允许的请求头
                .allowCredentials(true) // 是否允许发送凭证(如 cookies)
                .maxAge(3600); // 预检请求的缓存时间(秒)
    }
}

3. 使用 CorsFilter

如果你需要更细粒度的控制,可以通过自定义 CorsFilter 来实现。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsFilterConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true); // 允许发送凭证
        config.addAllowedOrigin("https://example.com"); // 允许的源
        config.addAllowedHeader("*"); // 允许的请求头
        config.addAllowedMethod("*"); // 允许的 HTTP 方法

        source.registerCorsConfiguration("/**", config); // 对所有路径生效
        return new CorsFilter(source);
    }
}

4. Spring Security 中配置 CORS

如果你的应用使用了 Spring Security,需要在 Spring Security 的配置中显式启用 CORS 支持。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(cors -> cors.configurationSource(corsConfigurationSource())) // 启用 CORS
            .csrf(csrf -> csrf.disable()) // 禁用 CSRF(如果需要)
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);
        config.addAllowedOrigin("https://example.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

5. CORS 配置选项说明

  • allowedOrigins: 允许的源(域名),可以指定多个,例如 "https://example.com""*"(允许所有源)。
  • allowedMethods: 允许的 HTTP 方法,例如 GETPOSTPUT 等。
  • allowedHeaders: 允许的请求头,例如 "*" 表示允许所有请求头。
  • allowCredentials: 是否允许发送凭证(如 cookies)。
  • maxAge: 预检请求的缓存时间(秒)。

总结

Spring Boot 提供了多种灵活的方式来处理跨域请求:

  1. @CrossOrigin 注解:适用于方法或类级别的细粒度控制。
  2. 全局配置:通过 WebMvcConfigurer 实现,适用于整个应用。
  3. CorsFilter:适用于需要更复杂控制的场景。
  4. Spring Security 配置:在 Spring Security 中启用 CORS 支持。

根据具体需求选择合适的方式即可。

THE END
点赞9 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容