개발_TIL
개발_TIL | 2022-05-23(25)
Hee94
2022. 5. 23. 23:12
▷ 머신러닝 프로젝트 시작(4)
< 소셜 로그인 구현(feat.Kakao) > (2)
저번 주에 이어 카카오 소셜 로그인 연동에 대해 알아보면서 해결 하지 못한 카카오 로그인과 우리 웹페이지 서비스와
연동을 해보았다.
def getAccessToken(clientId, code): # 세션 코드값 code 를 이용해서 ACESS TOKEN과 REFRESH TOKEN을 발급 받음
url = "https://kauth.kakao.com/oauth/token"
payload = "grant_type=authorization_code"
payload += "&client_id=" + clientId
payload += "&redirect_url=http%3A%2F%2Flocalhost%3A5005%2Foauth&code=" + code
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'Cache-Control': "no-cache",
}
reponse = requests.request("POST", url, data=payload, headers=headers)
access_token = json.loads(((reponse.text).encode('utf-8')))
return access_token
##kakao profile-list##
def kakaoprofile(accessToken):
url = "https://kapi.kakao.com/v2/user/me"
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Authorization': "Bearer " + accessToken,
}
response = requests.request("GET", url, headers=headers)
access_token = json.loads(((response.text).encode('utf-8')))
return access_token
우선 카카오 디벨로퍼로 부터 Access_Token을 받은후 밑의 코드를 이용하였다.
@blueprint.route('/oauth', methods=["GET"])
def oauth():
code = str(request.args.get('code'))
# XXXXXXXXX 자리에 RESET API KEY값을 사용
resToken = getAccessToken("XXXXXXXXXXXXXXXXX", str(code))
print(resToken)
profile = kakaoprofile(resToken['access_token'])
print(profile['kakao_account']['email'])
print(profile['id'])
email = profile['kakao_account']['email']
id = profile['id']
user = db.member.find_one({'email': email})
if user is None:
db.member.insert_one({'email': email, 'id': id})
result = db.member.find_one({
"email": email,
"id": id,
})
if result is None:
return jsonify({'message': 'fail'}), 401
payload = {
'id': str(result['_id']),
'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24) # 토큰 시간 적용
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
return jsonify({'message': 'success', 'token': token})
카카오에서 받은 토큰으로 내 카카오 계정의 이메일과 id고유번호를 가지고와 db에 저장시켜준 후 웹페이지 서비스에
가입시켜 주었다.