안녕하세요 쿤드입니다. 🍀

 

가끔씩 보고 싶은 정보들을 모아 블로그에서 보고 싶을때 정보를 쫙 모아다가

Tistory의 OpenAPI를 이용해서 올리곤 했었습니다. (가끔이라서 수동으로 함)

 

오늘 오랜만에 좀 보려고 했는데

자꾸 400 Error가 발생하고 이유는 모르겠고.. 뒤져보니 response_type=code 방식을 이용해서 

하라고 하는 것을 보니 뭔가 변경된것 같았습니다.

 

Open API 사용하기 위한 App 등록이 선행되어야 하는데
이는 검색하면 많이 나와서 넘어갑니다.

 

자세히 Autoriztion Code 방식을 읽어보니 기존에 제가 인증받아서 사용하던 code에서 끝나는 것이 아니라

그 code를 가지고 token을 받아서 그 token을 이용해야 하는 것이 었습니다.

 

그래서 방법은 총 3단계 (기존엔 2단계)

  1. Tistory Login
  2. Authentication code 발급
  3. Access Token 발급

 

확인하는 방법은 2가지가 있습니다.

웹브라우저에서 해보거나, 뭐가 되었든 코드로 짜서 자동으로 하거나

우선은 수동으로 먼저 확인해봅니다. python3 코드는 이 페이지 하단에서 볼 수 있습니다.

 

웹브라우저에서 직접 해본다.

1번 과정 - https://www.tistory.com 로그인한다.

2번 과정 - Autentication Code 발급 받는다.

웹 브라우저에 입력할 내용

https://www.tistory.com/oauth/authorize?client_id=app의 ClientID&redirect_uri=리다이렉션 받을 URI&response_type=code  

 

예시(아래 것은 샘플이라 에러페이지 나옴, client_id에 임의의 값을 넣어서 되지 않음, redirection은 내 맘대로함)

https://www.tistory.com/oauth/authorize?client_id=d962867605b93asdfasdfasd6fb96f8cc27568b141c&redirect_uri=sfixer.tistory.com&response_type=code

 

 

 

3. Access Token을 발급 받는다.

웹 브라우저에 입력할 내용

www.tistory.com/oauth/access_token?client_id=나의 CLIENT_IDc&client_secret=나의 CLIENT_SECRET&redirect_uri=설정한 redirect uri &code=2번과정에서 받아온 code 정보&grant_type=authorization_code

 

예시 (샘플이라 아무정보나 들어있음, 본인것에 맞게 바꿔야함)

www.tistory.com/oauth/access_token?client_id=ddszxcvzxcv36fb96f8cc27568b141c&client_secret=d962867zxcvzxcvelkasjdflkjasldk51ca867454aac07d9b98bde63553ba3d8a93&redirect_uri=sfixer.tistory.com&code=a1175b123409821093saldjfklasdjflkasdjflke91c5a3dc8b4514268a4e3a066&grant_type=authorization_code

 

 

코드로 구현한다

 

위에 처럼 해도되지만 간단하게 파이썬 코드 몇줄로 3단계 동작을 수행하겠습니다. 

개인정보들은 환경변수에 등록해서 가져와서 썼기때문에 그 부분만 따로 (하드코딩이든 뭐든) 처리해주시면 동작합니다.

테스트까지는 해보았습니다.

물론 아래의 제가 한 코드보다 훨씬 더 간결하게 구현이 가능할 것입니다. 

이를 공유한 이유는 저 처럼 삽질하는 사람을 좀 돕고자 공유했습니다.

 

Python3.8.5을 사용했으며

사용했던 패키지 버전 정보입니다.

  • requests==2.24.0
  • selenium==3.141.0
#!/usr/bin/env python3
import os
import re
from requests import get
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


# tistory에 로그인을 합니다.
def tistory_login():
    tistory_id = os.environ.get('TISTORY_ID')
    tistory_pw = os.environ.get('TISTORY_PW')
    chromedriver_path = os.environ.get('CHROMEDRIVER_PATH')
    chrome_options = Options()
    chrome_options.add_argument("--headless")  # chrome 띄워서 보려면 주석처리
    driver = webdriver.Chrome(chromedriver_path, options=chrome_options)
    driver.implicitly_wait(3)
    driver.get('https://www.tistory.com/auth/login?redirectUrl=http%3A%2F%2Fwww.tistory.com%2F')
    driver.find_element_by_name('loginId').send_keys(tistory_id)
    driver.find_element_by_name('password').send_keys(tistory_pw)
    driver.find_element_by_xpath('//*[@id="authForm"]/fieldset/button').click()
    return driver


# authentication code 정보를 가져옵니다.
def get_authentication_code(driver, client_id, redirect_url):
    req_url = 'https://www.tistory.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code&state=langoo' % (client_id, redirect_url)
    driver.get(req_url)
    driver.find_element_by_xpath('//*[@id="contents"]/div[4]/button[1]').click()
    redirect_url = driver.current_url
    temp = re.split('code=', redirect_url)
    code = re.split('&state=', temp[1])[0]
    return code


# http://www.tistory.com/guide/api/index
# access token 정보를 가져옵니다.
def get_access_token(code, client_id, client_secret, redirect_url):
    url = 'https://www.tistory.com/oauth/access_token?'
    payload = {'client_id': client_id,
               'client_secret': client_secret,
               'redirect_uri': redirect_url,
               'code': code,
               'grant_type': 'authorization_code'}
    res = get(url, params=payload)
    token = res.text.split('=')[1]
    return token


def main():
    client_id = os.environ.get('TISTORY_CLIENT_ID')
    client_secret = os.environ.get('TISTORY_CLIENT_SECRET')
    redirect_url = os.environ.get('TISTORY_REDIRECT')
    driver = tistory_login()
    code = get_authentication_code(driver, client_id, redirect_url)
    token = get_access_token(code, client_id, client_secret, redirect_url)
    print(token)


if __name__ == '__main__':
    main()
반응형

'기타' 카테고리의 다른 글

빙크스의 술 (ビンクスの酒) 번역, 가사  (7) 2023.03.12
Jenkins 사용자 목록 curl로 가져오기  (851) 2020.12.29
테넌트  (656) 2020.07.23
TCP Status 상태에 대해서  (433) 2020.07.15
TCP 통계수치 변화 (장애 상황)  (1029) 2020.07.15

+ Recent posts