본문 바로가기

오픈소스/스프링

[Spring] CORS with Spring Framework

 

 CORS 필터 에 설명 및 코드는 다음 페이지를 확인해주세요. https://junhokims.tistory.com/29

 

[Spring] CORS Filter 적용

 CORS 에 대해 설명하고자 합니다. Cross-Origin Resource Sharing 의 약자로써, 특정 헤더를 통해 브라우저에게 Origin 에서 실행되고 있는 웹 애플리케이션이 Cross-Origin에 리소스에 접근할 수 있는 권한..

junhokims.tistory.com

 

 CORS 필터  의 단점은 GET 메소드만 이용할 수 있다는 단점이 있습니다. 하지만 Spring에서 지원하는 프레임워크를 사용하면 간단하게 적용할 수 있습니다. 즉, Spring Framework 4.2 GA 는 CORS를 기본적으로 지원 하므로 일반적인 필터 기반 솔루션 보다 쉽고 강력하게 구성할 수 있습니다.

 

 본 문서는 https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#xml-namespace 를 참고하였습니다. 또한 XML 방식으로 처리 함으로써 좀 더 유연하고 직관성 있게 코드를 짜보았습니다. XML 외의 방식은 아래 블로그를 참고해주세요.

 

CORS support in Spring Framework

 

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin. For example, as you’re checking your bank account in one tab, you could have the evil.com website in another tab. The scripts from evil.com shouldn’

spring.io

 

 

# Contents


  • CORS XML 적용

 

 

# CORS XML 적용


0. Spring Version Check

본 블로그에서는 Spring Version 4.2.0 을 기준으로 작성하고 있습니다.

에러가 뜨신다면 pom.xml에서 4.2.0 버전으로 버전으로 바꿔서 진행해주시기 바랍니다.

 

 

 

1. cors-config.xml 생성

먼저 CORS를 적용시키기 위한 환경설정 xml 파일을 만들어야 합니다.

src/main/resource - 우클릭 - New - Other을 눌러주세요. 그리고 xml을 생성해주시기 바랍니다.

 

 

 

resources 폴더를 클릭한 후, config 파일이 없으면 아래와 같이 생성하고 

파일명은 cors-config 라고 명칭합니다.

 

 

 

코드는 다음과 같습니다.

<?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>
		<mapping path="/**" allowed-origins="*"/>
	</cors>
	
	<!-- 아래는 특정 도메인 허용
    <cors>
        <mapping path="/**" allowed-origins="http://localhost:1841"/>
    </cors>
    
    !-->
 
    <!-- 아래는 여러 특정 도메인 허용
    <cors>
        <mapping path="/**" allowed-origins="http://localhost:1841, http://localhost:1234, http://localhost:5678"/>
    </cors>
    
    -->
    
</beans:beans>

 

2. servlet-context.xml 수정

 servlet-context.xml 로 이동 합니다. 

 경로는 다음과 같습니다.

 

 

 

 그리고 아래 코드를 추가해주세요.

<beans:import resource="classpath:config/cors-config.xml"/>

 

 이로써 간단하게 Spring에서 CORS 설정을 하였습니다. 

 본 예제는 필터 적용 예제보다 편리하고 모든 메소드를 지원하기 때문에 버전 변경이 에러가 떠서 버전변경이 어렵지 않은 이상 이러한 설정을 적극적으로 추천합니다.