@CrossOrigin 业务场景使用案例
@CrossOrigin
注解用于启用跨源请求(CORS)。CORS 是一种机制,它允许不同源的前端应用(例如,位于不同域名的 Web 应用)访问你的后端 API。
业务场景:
例如你正在开发一个开放的 API,允许第三方开发者使用你的服务。这些开发者可能会从他们自己的网站向你的 API 发送请求。由于浏览器的同源策略,如果 API 服务器没有正确配置 CORS,前端应用将无法成功调用你的 API。
1. 单个控制器或方法的 CORS 配置:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://xopencode.com") // 允许指定域名的前端应用访问
public class OpenApiController {
@GetMapping("/api/data")
public Data getData() {
// 返回 API 数据
return new Data(...);
}
}
在这个例子中,只有 http://example.com
这个域名的前端应用可以访问 /api/data
路径下的资源。
2. 全局 CORS 配置:
import org.springframework.context.annotation.Bean;
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 WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") // 应用于 /api/ 下的所有路径
.allowedOrigins("http://xopencode.com", "https://anotherdomain.com") // 允许多个域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
.allowedHeaders("*") // 允许的头
.allowCredentials(true) // 允许携带凭证
.maxAge(3600); // 预检请求的缓存时间
}
}
在这个全局配置中,我们为所有 /api/
路径下的请求设置了 CORS 规则,允许来自 http://example.com
和 https://anotherdomain.com
的请求,并允许使用 GET、POST、PUT 和 DELETE 方法。
3. 处理预检请求:
当浏览器自动发送 OPTIONS 请求(预检请求)时,服务器需要正确响应这些请求以告知浏览器允许的 HTTP 方法。
@Controller
public class PreFlightController {
@CrossOrigin
@RequestMapping(method = RequestMethod.OPTIONS)
public ResponseEntity<?> handlePreFlightRequest(HttpServletResponse response) {
return ResponseEntity.ok().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
.header("Access-Control-Allow-Headers", "Content-Type, X-Custom-Header")
.allowCredentials(true)
.build();
}
}
4. 测试 CORS:
- 前端开发者将使用
http://xopencode.com
或https://anotherdomain.com
作为前端应用的域名,向你的 API 发送请求。 - 当他们发送请求时,浏览器会先发送一个 OPTIONS 请求进行预检。
- 服务器通过
@CrossOrigin
注解或全局 CORS 配置,返回允许的 HTTP 方法和头信息。 - 浏览器随后会根据预检请求的响应决定是否允许实际的请求。
总结:
@CrossOrigin
注解允许开发者明确地指定哪些源可以访问他们的 API,从而提高了应用程序的安全性。- 它简化了 CORS 配置,使得开发者可以轻松地为特定的控制器或方法启用跨源请求。
- 使用
@CrossOrigin
注解可以提高 API 的可用性,使其能够被多个前端应用安全地访问。
转载自:https://juejin.cn/post/7383029376381747237