是什么

Cross Origin Resource Sharing:跨源资源共享。
由于同源策略(浏览器的实现的基础安全策略),当前域的资源不允许被其他域的请求所访问,这种机制阻止恶意站点读取另一个站点的数据,但也把合法的读取也给禁了。所以需要一些方案来放开这个限制。
CORS是其中一个方案,也是最常用且推荐的方案。

方案描述

CORS说白了就是类似白名单的机制,可以配置请求来自不同源的是否可以获取本站资源。

  1. 浏览器发起请求时,会默认在请求header中带上一个Origin,标识请求来源。
  2. 服务器识别到这个Origin之后,如果允许访问,就需要在response带上Access-Control-Allow-Origin这个header并指定请求来源(*代表支持所有来源)。image.png
  3. 当浏览器看到带有适当Access-Control-Allow-Origin标头的响应时,浏览器允许与客户端站点共享响应数据。

    spring如何配置跨域

    为特定请求跨域

    1. @RestController
    2. @RequestMapping("/account")
    3. public class AccountController {
    4. @CrossOrigin
    5. @RequestMapping(method = RequestMethod.GET, path = "/{id}")
    6. public Account retrieve(@PathVariable Long id) {
    7. // ...
    8. }
    9. @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    10. public void remove(@PathVariable Long id) {
    11. // ...
    12. }
    13. }

    controller跨域

    1. @CrossOrigin(origins = "http://example.com", maxAge = 3600)
    2. @RestController
    3. @RequestMapping("/account")
    4. public class AccountController {
    5. @RequestMapping(method = RequestMethod.GET, path = "/{id}")
    6. public Account retrieve(@PathVariable Long id) {
    7. // ...
    8. }
    9. @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    10. public void remove(@PathVariable Long id) {
    11. // ...
    12. }
    13. }

    全局跨域

    1. @Configuration
    2. @EnableWebMvc
    3. public class WebConfig implements WebMvcConfigurer {
    4. @Override
    5. public void addCorsMappings(CorsRegistry registry) {
    6. registry.addMapping("/**");
    7. }
    8. }