跨域入门
跨域入门
1、简介
跨域全称是跨域资源共享(Cross-Origin Resources Sharing,CORS
),它是浏览器的保护机制,只允许网页请求统一域名下的服务,同一域名指=>协议、域名、端口号都要保持一致,如果有一项不同,那么就是跨域请求。在前后端分离的项目中,需要解决跨域的问题。
CORS
配置
2、SecurityFilterChain
中配置 CORS
2.1、在 使用 SecurityFilterChain
和 CorsConfigurationSource
来配置 CORS
,而不再推荐使用 WebSecurityConfigurerAdapter
。
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors() // 启用 CORS 支持
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated() // 保护 API 路径
.and()
.formLogin().disable(); // 示例禁用表单登录,实际配置根据需要
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:3000"); // 允许跨域的域名
configuration.addAllowedMethod("*"); // 允许所有 HTTP 方法
configuration.addAllowedHeader("*"); // 允许所有头
configuration.setAllowCredentials(true); // 允许携带 cookies
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 注册 CORS 配置
return source;
}
}
在这个配置中:
http.cors()
启用 Spring Security 的CORS
支持。CorsConfigurationSource
Bean 提供了CORS
配置,允许跨域的源、方法、头等。- 使用
http.build()
来构建SecurityFilterChain
。
SecurityFilterChain
中的 CORS
配置优先级
2.2、需要注意,SecurityFilterChain
中的 CORS
配置优先级高于 Spring MVC 的全局 CORS
配置。因此,如果你需要通过 Spring Security 来控制 CORS
策略,必须在 SecurityFilterChain
配置中显式启用。
CORS
配置
3、局部 除了全局 CORS
配置外,你还可以通过 @CrossOrigin
注解来在特定的控制器或方法上启用 CORS。这对于只需要允许某些控制器或路径跨域的场景非常有用。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@CrossOrigin(origins = "http://localhost:3000") // 只允许来自 http://localhost:3000 的请求
@GetMapping("/api/data")
public String getData() {
return "Hello from API";
}
}
@CrossOrigin
注解可以直接应用于方法级别或类级别,支持配置如 origins
、methods
、allowedHeaders
、exposedHeaders
等属性,允许你精细化控制哪些源可以访问指定的资源。
CORS
预检请求
5、浏览器会在某些跨域请求(如发送 POST
请求时,携带自定义头部或 Cookies)之前,先发起一个 预检请求(OPTIONS 请求)来询问服务器是否允许跨域请求。这是浏览器的安全机制,用来确认目标服务器是否接受实际的请求。
预检请求的处理
在 Spring Boot 中,预检请求通常会自动处理。如果你有 CORS
配置,Spring Boot 会根据配置自动返回 200 OK
响应,表示允许跨域请求。
例如,如果配置了 allowedOrigins("http://localhost:3000")
,并且浏览器发送了一个跨域的 OPTIONS
请求,Spring Boot 会返回一个适当的 CORS
响应头,允许该请求继续。