카카오 로그인 API를 서비스에서 연동하기 위해서는 여러 절차를 거쳐야 한다. 제대로 연동하기 위해서는 절차에 대한 이해가 선행되어야 한다.
[그림1] 카카오 로그인 API 프로세스
출처: https://data-jj.tistory.com/53
Host: kauth.kakao.com
GET /oauth/authorize?client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}&response_type=code HTTP/1.1
[그림3] 인가 코드 받기
최종 요청 형태는 아래와 같다.
https://kauth.kakao.com/oauth/authorize?client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}&response_type=code
http://localhost:3000/asdf/asdf?code={발급된 인가 코드}
Host: kauth.kakao.com
POST /oauth/token HTTP/1.1
Content-type: application/x-www-form-urlencoded;charset=utf-8
[그림3] 카카오 토큰 받기
def get_kakao_token(code):
auth_code = code
kakao_token_api = "https://kauth.kakao.com/oauth/token"
data = {
"grant_type" : 'authorization_code',
"client_id" : KAKAO_REST_API_KEY,
"redirect_uri" : KAKAO_REDIRECT_URI,
"code" : auth_code
}
headers = {'Content-type' : 'application/x-www-form-urlencoded;charset=utf-8'}
requests.post(kakao_token_api, headers=headers, data=data)
access_token = token_response.json().get('access_token')
body
{
"access_token":"",
"token_type":"bearer",
"refresh_token":"",
"id_token":"",
"expires_in": int_type,
"scope":"account_email openid profile_nickname",
"refresh_token_expires_in": int_type
}
Host: kapi.kakao.com
GET/POST /v2/user/me HTTP/1.1
Authorization: Bearer ${ACCESS_TOKEN}
Content-type: application/x-www-form-urlencoded;charset=utf-8
headers = {
"Authorization": f"Bearer {access_token}",
"Content-type" : "application/x-www-form-urlencoded;charset=utf-8"
}
user_info_response = requests.post("https://kapi.kakao.com/v2/user/me", headers=headers).json()
headers
[requests에 대한 응답을 json으로 수신]
응답에 유효한 JSON이 포함되어 있으면 Response 객체에서 .json() 메서드를 사용하여 디코딩 된 결과를 얻는다. json() 메서드를 사용하지 않으면 응답 코드만을 받기 때문에 꼭 .json()을 사용해서 다른 정보까지 받는다.
{
'id': int_type,
'connected_at': '연결 시간',
'properties': {'nickname': '닉네임'},
'kakao_account':
{
'profile_nickname_needs_agreement': False,
'profile': {'nickname': '닉네임'},
'has_email': True,
'email_needs_agreement': False,
'is_email_valid': True,
'is_email_verified': True,
'email': '이메일'
}
}