2014년 5월 13일 화요일

CORS (Cross-origin resource sharing) 간략한 설명

Wiki: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

대략적 내용만 정리합니다.

개요

  • 보안상 문제로 어느 시기 부터 웹 브라우저들이 AJAX 로 외부 host 로 접속하는 걸 막기 시작했습니다.
    • 예를 들어 AJAX 로 http://www.google.com 와 같이 외부 host url 로 접속하는게 불가능 해지고 /relative-path/mypage.html 과 같이 현재 host 의 하부 경로로만 접근 가능합니다.

CORS 가 필요한 시점

  • 그러나 AJAX 로 외부 접근이 필요한 경우에 Response header 에 field 를 추가하여 접근 허용 범위를 정할 수 있습니다
  • Header field 에  Access-Control-Allow-Origin 를 추가해 줍니다.
    • Access-Control-Allow-Origin: http://www.example-social-network.com
  • 위와 같이 특정 host 로 부터 접근을 허용할 수도 있고 아래와 같이 모든 접근을 허용할 수도 있습니다.
    • Access-Control-Allow-Origin: *

테스트 방법

  • 2대의 PC (IP 주소가 다른 2대의 서버 환경) 에 서버를 구동합니다.
  • 192.168.0.2 와 192.168.0.3 IP 주소를 사용하는 서버가 있다고 가정합니다.
  • 192.168.0.2 서버의 웹 페이지에 접속해서 AJAX 로 192.168.0.3 서버의 웹 페이지를 접근 하겠습니다.

192.168.0.2 (Apache tomcat)

파일 : cors.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>CORS test</title>
        <style type="text/css">
            #result {border:solid 1px black;}
        </style>
        <script type="text/javascript">
            function $(obj) {
                return (obj instanceof String || typeof obj === "string") ? document.getElementById(obj) : obj;
            }
            function getXMLHttpRequest() {
                if (window.ActiveXObject) {
                        try {
                                return new ActiveXObject("Msxml2.XMLHTTP");
                        } catch (e) {
                                try {
                                        return new ActiveXObject("Microsoft.XMLHTTP");
                                } catch (e1) {
                                        return null;
                                }
                        }
                } else if (window.XMLHttpRequest) {
                        return new XMLHttpRequest();
                } else {
                        return null;
                }
            }
            function action(url) {
                var ajax = getXMLHttpRequest();
                ajax.onreadystatechange = function() {
                    switch (ajax.readyState) {
                        case 1:
                        case 2:
                        case 3:
                            break;
                        case 4:
                            if (ajax.status === 200) {
                                $("result").innerHTML = ajax.responseText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r/g, "").replace(/\n/g, "<br />");
                            } else {
                                $("result").innerHTML = "AJAX request failed with status code: " + ajax.status;
                            }
                            break;
                    }
                };
                ajax.open("GET", url, true);
                ajax.send();
            }
        </script>
    </head>
    <body>
        <h1>CORS test</h1>
        <button onclick="action('http://192.168.0.3/apps/hello.html');return false;">Action</button>
        <div id="result">
            ...
        </div>
    </body>
</html>


192.168.0.3 (apache + php)

파일 : apps/hello.html
<?php
header('Access-Control-Allow-Origin:*');
?>
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello</h1>
<p>If you get this message via AJAX request, you are allowed to access me.</p>
</body>
</html>


테스트 결과

  • http://192.168.0.2:8080/MyApp/cors.jsp 에 접속해서 Action 버튼을 누르면 192.168.0.3 서버의 apps/hello.html 파일에 접근해서 해당 내용을 div 에 표시합니다.


  • 192.168.0.3 서버의 apps/hello.html 의 아래 부분을 주석 처리하면 아래와 같이 실패할 것입니다.
<?php
//header('Access-Control-Allow-Origin:*');
?>

Firefox 로 테스트 하였습니다.


JSP 페이지에 header 를 추가하려면 다음과 같이 할 수 있습니다.
<%
    response.addHeader("Access-Control-Allow-Origin", "*");
%>

댓글 없음:

댓글 쓰기