본문 바로가기

개발이야기/web programming

Rest api에서 Content-Type 헤더의 역할 및 Spring boot 예제

 

 

Rest api를 개발할 때 사용하는 Content-Type의 역할, 그리고 예제를 통해 어떻게 헤더의 정보를 활용하는지 알아보자.

 

Content-Type Header?

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

- w3.org

 

Http request를 통해 data가 전달될 때, 데이터의 종류를 친절하게 가이드 해 줄수 있는 정보이다. 즉, Content-Type Header을 통해 해당 request에 대한 data(body)에 대한 동작을 제어 할수있다.

Content-Type Header 종류

IANA(Internet Assigned Numbers Authority)에서 공식적인 MIME 미디어 타입을 관리한다.
 

Content-Type에 따른 다른 동작 예제

Spring boot의 @RestController을 활용하여 간단히 Content-Type이 존재하는 api와 존재하지 않는 api를 작성했다.

둘 다 json형태의 String을 반환한다.

package hello;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CallController {

    @GetMapping("/without")
    public String withoutType() {
        return "{\"name\":\"wonyoung\"}";
    }

    @GetMapping(value ="/with", produces = "application/json; charset=UTF-8")
    public String withType() { //Content-Type에 대한 정의를 추가.
        return "{\"name\":\"wonyoung\"}";
    }
}
 

아래는 상기 api를 호출 할 html 코드이다.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#button01").click(function () {
                $.ajax({
                    url: "http://localhost:8090/without",
                    type: 'GET',
                    success: function (result) {
                        alert("result : " + result);
                    }
                });
            });

            $("#button02").click(function () {
                $.ajax({
                    url: "http://localhost:8090/with",
                    type: 'GET',
                    success: function (result) {
                        alert("result : " + result + "\nresult.name : " + result.name);
                    }
                });
            });

        });
    </script>
</head>
<body>
<button id="button01">Call without content-type</button>
<br>
<button id="button02">Call with content-type</button>
</body>
</html>

 

Content-Type에 따른 다른 동작 실행

스크린샷. html 동작화면

 

스크린샷. Content-Type이 없는 api를 호출 했을 때 반환 : String으로 auto type casting 됨.

 

스크린샷. Content-Type이 포함된 api를 호출 했을 때 반환 : Object로 auto type casting 됨.

 

 

 

Content-Type에 따른 다른 동작 실행방지?

Content-Type에 따른 auto casting과 같은 동작은 간편하지만, 보안에 취약점으로 사용될 수 있다고 한다.[각주:1]
아래 기능을 사용하여 auto casting과 같은 기능을 강제로 제지하고 사용하는 측에서 어떻게 사용할지 선언하여, 사용자가 원하는대로 동작하도록 유도 할 수있다.
 
X-Content-Type-Options: nosniff
 
End of Document.

 

  1. http://www.adambarth.com/papers/2009/barth-caballero-song.pdf [본문으로]
반응형