티스토리 뷰

백기선 - 스프링 부트 개념과 활용

CORS

  • SOP와 CORS

    • Single-Origin Policy

      • 단일 Origin에만 요청을 보낼 수 있다는 것을 의미하는 정책

      • 기본적으로 SOP가 적용되어 있어서, Origin이 다르면 호출할 수 없다.

      • REST API가 http://localhost:8080 을 통해서 서비스 되고있고, 18080 포트를 사용하는 애플리케이션에서 그 REST API를 호출하려고 한다. 기본적으로 SOP에 위반 되기 때문에 호출하지 못한다.

    • Cross-Origin Resource Sharing

      • SOP를 우회하기 위한 표준

      • 서로 다른 Origin이 리소스를 공유할 수 있는 기술

  • Origin?

    • URI 스키마 (http, https)

    • hostname (io.namjune, localhost)

    • 포트(8080, 18080)

  • Spring MVC @CrossOrigin

    • 스프링 부트에서 @CrossOrigin에 관한 빈 설정들을 자동으로 해주기 때문에 그냥 사용하면 된다. 또는 WebMvcConfigurer 사용해서 글로벌로 설정할 수 있다.

    • @Controller나 @RequestMapping에 추가하거나

      @RestController
      @RequestMapping("/account")
      public class AccountController {

         @CrossOrigin
         @GetMapping("/{id}")
         public Account retrieve(@PathVariable Long id) {
             // ...
        }

         @DeleteMapping("/{id}")
         public void remove(@PathVariable Long id) {
             // ...
        }
      }
      @CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
      @RestController
      @RequestMapping("/account")
      public class AccountController {

         @GetMapping("/{id}")
         public Account retrieve(@PathVariable Long id) {
             // ...
        }

         @DeleteMapping("/{id}")
         public void remove(@PathVariable Long id) {
             // ...
        }
      }
    • WebMvcConfigurer 사용해서 글로벌 설정

      • 모든 api를 localhost:9090에 CORS 허용하도록 등록

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
       @Override
       public void addCorsMappings(CorsRegistry registry) {
           registry.addMapping("/**")
              .allowedOrigins("http://localhost:9090");
      }
    }
  • ajax로 CORS 동작 확인하기

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>
<h1>CORS Test</h1>
<script src="/webjars/jquery/dist/jquery.min.js"></script>
<script>
 $(function() {
   $.ajax("http://localhost:8080/hello")
      .done(function(msg) {
         alert(msg);
      })
      .fail(function() {
         alert("fail");
      });
});
</script>
</body>
</html>






댓글