티스토리 API 연동

프로그래밍|2018. 9. 18. 13:50

내가 관리하고 있는 티스토리의 게시물을 랜덤하게 추출해 보고 싶었다.

확인해 보니 티스토리에서 이미 API를 제공해 주고 있었기에 어렵지 않게 구현해 볼 수 있었다.


내가 원하는 연동 방식은 server to server 이고 access token을 발급 받는 과정이 필요했다. access token을 발급 받으면 해당 토큰으로 server to server 연동이 가능하다.


[1]

먼저 OAuth 인증을 위해 클라이언트를 등록해야 한다.

https://www.tistory.com/guide/api/oauth 페이지로 이동하여 "클라이언트 등록" 버튼을 클릭하자.

입력폼에 서비스 URL과 CallBack 경로는 http://localhost:8080/tistoryCallback 으로 설정하였다.



[2]

클라이언트 등록이 완료되면 Client ID와 Secret Key를 발급 받는다.



[3]

인증 요청 단계

위에서 발급 받은 client ID를 이용하여 Tistory 서버에 인증을 받는 단계이다.

1
2
3
4
@RequestMapping(value = "/tistoryAuthorization", method = RequestMethod.GET)
public String tistoryAuthorization() {
    return "tistoryAuthorization";
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE HTML>
<html>
<head>
    <title>Authorization Code</TITLE>
</head>
<body>
<form method="GET" action="https://www.tistory.com/oauth/authorize/">
    <input type="hidden" name="client_id" value="클라이언트아이디"/>
    <input type="hidden" name="redirect_uri" value="http://localhost:8080/tistoryCallback"/>
    <input type="hidden" name="response_type" value="code"/>
    <button type="submit">Request Authorization Code</button>
</form>
</body>
</html>
cs


위의 코드를 추가 후 로컬에서 서버를 띄운다.

그리고 http://localhost:8080/tistoryAuthorization 에 접속 후 버튼을 클릭하자.



[4]

인증 확인 및 Authorization code 발급

티스토리 서버는 전달 받은 client_id와 redirect_uri의 정보를 확인하여 유효하다면 티스토리 로그인 페이지로 리다이렉트 시킨다.

로그인을 하면 CallBack에 등록한 URL로 Authorization code를 파라미터로 전달해 준다. (파라미터 name은 code)

여기서 내가 삽질한 경험을 공유한다.

나는 http://localhost:8080/tistoryCallback 의 URL로직에 단순히 code 파라미터를 받고 print 하였다.

그리고 나서 access token을 발급 받기 위한 작업을 진행하였다. 헌데 유효하지 않은 토큰이라는 오류가 지속적으로 발생하는 거였다.

그래서 다음과 같이 code를 넘겨 받으면 그즉시 access token을 발급해주는 API에 요청을 보냈다. 그랬더니 잘 됨. 나이쑤~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ResponseBody
@RequestMapping(value = "/tistoryCallback", method = RequestMethod.GET)
public String tistoryCallback(@RequestParam String code) throws Exception {
    URI uri = UriComponentsBuilder.newInstance()
            .scheme("https").host("www.tistory.com")
            .path("/oauth/access_token")
            .queryParam("client_id", clientId)
            .queryParam("client_secret", clientSecret)
            .queryParam("redirect_uri""http://localhost:8080/tistoryCallback")
            .queryParam("code", code)
            .queryParam("grant_type""authorization_code")
            .build().encode().toUri();
 
    String accessToken = restTemplate.getForObject(uri, String.class);
    return accessToken;
}
cs



[5]

access token을 발급 받았으니 이제 https://www.tistory.com/guide/api/index 페이지에서 사용할 수 있는 API들을 연동하자.

블로그 정보 가져오기

1
2
3
4
5
6
7
URI blogUri = UriComponentsBuilder.newInstance()
                .scheme("https").host("www.tistory.com")
                .path("/apis/blog/info")
                .queryParam("access_token", accessToken)
                .queryParam("output""json")
                .queryParam("blogName""블로그이름")
                .build().encode().toUri();
cs


댓글()