Java/Spring

[Spring] Spring CORS설정

jwKim96 2019. 7. 20. 19:40

[추천글..]

 

[Sencha] extjs+spring에서 jsonp 적용하기

 

 

위 글에서는 cors요청을 위해 jsonp를 적용하였지만, jsonp의 장점이자 결정적인 단점이 있다.

 

그것은 바로, GET 요청으로 javascript를 요청하고 받는다는 것이다.

 

 

이 말은 즉, GET요청만 가능하기 때문에 CRUD(Create  Read  Update  Delete) 기능을 모두 구현하는것은 제한적이다.

 

일반적으로 Create, Update의 경우 데이터를 전송하기때문에 정보 보호를 위해 POST방식으로 요청을 한다.

 

그러면 POST방식으로 요청을 하는 방법을 알아야 하는데, 하지만 POST method로 Cross-Origin에 요청을하면,

 

SOP(Same-Origin Polic)에 의해 요청이 제한된다.

 

하지만 Spring에서 간단한 설정만 하면 해결된다. (Spring Security 미적용)

 

 

설정에 사용할 파일은 총 두가지. servlet-context.xml 과 cors-config.xml 두가지이다.

 

먼저 cors-config.xml을 만들어 준다.

이미 만들어 두어서, 이미 존재한다는 메세지가 나온다

 

이 위치에 생성이 되었으면 xml의 namespace에서 mvc를 추가하고 아래 내용을 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <mvc:cors>
        <mvc:mapping path="/**" allowed-origins="*"/>
    </mvc:cors>
 
    <!-- 아래는 특정 도메인 허용-->
    <mvc:cors>
        <mvc:mapping path="/**" allowed-origins="http://localhost:1841"/>
    </mvc:cors>
 
    <!-- 아래는 여러 특정 도메인 허용-->
    <mvc:cors>
        <mvc:mapping path="/**" allowed-origins="http://localhost:1841, http://localhost:1234, http://localhost:5678"/>
    </mvc:cors>
 
</beans>
 
cs

 

제일 위의 설정은 모든 경로로 오는 모든 도메인으로부터의 요청을 허용한다는 설정.

 

그 아래 두번째는 특정 도메인만 허용.

 

세번째는 복수의 도메인을 허용한다는 의미이다.

 

상황에 따라 선택해서 사용하면 된다.

 

 

그리고 servlet-context.xml에서 cors설정파일을 import해주어야 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
 
    ... 생략
    
    <!-- CORS setting : https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#xml-namespace-->
    <beans:import resource="classpath:config/cors-config.xml"/>
    
    ... 생락
    
    
</beans:beans>
 
cs

 

서버를 재시작하고 나면 Cross-Domain에서 보내는 모든 요청이 정상적으로 동작한다.

 

 

 

 

 

참고 : https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#xml-namespace