카카오 개발자 문서 링크 : KAKAO DEVELOPERS LINK
http://localhost:8000
) 적용http://localhost:8000/user/kakao/callback
필수
or 선택
동의(권한) 설정인가 코드 발급
요청인가코드
는 토큰 받기에 필요한 값, 토큰에 부여될 권한 정보를 포함redirect_uri
에 전달redirect_uri
로 HTTP 302 Redirect
Location
에 인가 코드가 담긴 쿼리 스트링을 포함import jwt
import requests
from django.shortcuts import redirect
class KakaoSignInView(View):
def get(self, request):
client_id = settings.KAKAO_CLIENT_ID
kakao_auth_id = "https://kauth.kakao.com/oauth/authorize?response_type=code"
redirect_uri = "http://localhost:8000/user/kakao/callback"
return redirect(
f"{kakao_auth_id}&client_id={client_id}&redirect_uri={redirect_uri}"
)
class KakaoCallBackView(View):
def get(self, request):
kakao_token_api = "https://kauth.kakao.com/oauth/token"
data = {
"grant_type" : "authorization_code",
"client_id" : settings.KAKAO_CLIENT_ID,
"redirect_uri": "http://localhost:8000/user/kakao/callback",
"code" : request.GET.get("code")
}
access_token = requests.post(kakao_token_api, data=data).json().get('access_token')
# access_token = requests.post(kakao_token_api, data=data).json()['access_token']
# return JsonResponse({"token" : access_token})
user_info = requests.get('https://kapi.kakao.com/v2/user/me', headers={"Authorization": f"Bearer {access_token}"}).json()
# return JsonResponse({"user_info" : user_info})
아래와 같은 결과 값이 출력된다.
저장
, 정보가 이미 존재하면 바로 로그인(토큰발급)
kakao_id = user_info["id"]
kakao_name = user_info["properties"]["nickname"]
kakao_email = user_info["kakao_account"]["email"]
profile_image_url = user_info["properties"]["profile_image"]
if User.objects.filter(social_account_id = kakao_id).exists():
user = User.objects.get(social_account_id = kakao_id)
access_token = jwt.encode({"id" : user.id}, settings.SECRET_KEY, algorithm = settings.ALGORITHM
return JsonResponse({"message" : "SIGN IN SUCCESS", "token" : access_token}, status=200)
User(
social_account_id = kakao_id,
name = kakao_name,
email = kakao_email,
profile_image = profile_image_url,
social_id = Social.objects.get(name="kakao").id,
terms_agreements = {1:2},
).save()
user = User.objects.get(social_account_id=kakao_id)
access_token = jwt.encode({"id" : user.id}, settings.SECRET_KEY, algorithm = settings.ALGORITHM)
return JsonResponse({"message" : "ACCOUNT CREATED", "token" : access_token}, status=200)