https://developers.kakao.com/docs/latest/ko/kakaologin/common
RestApi키와 JavaScript 키를 쓸 예정
https://developers.kakao.com/tool/demo/login/login
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a id="custom-login-btn" href="javascript:loginWithKakao()">
<img
src="//k.kakaocdn.net/14/dn/btroDszwNrM/I6efHub1SN5KCJqLm1Ovx1/o.jpg"
width="222"
alt="카카오 로그인 버튼"
/>
</a>
<p id="token-result"></p>
<script src="https://developers.kakao.com/sdk/js/kakao.js"></script>
<script type="text/javascript">
Kakao.init('JAVASCRIPT_KEY');
function loginWithKakao() {
Kakao.Auth.authorize({
redirectUri: 'http://127.0.0.1:8000/oauth/redirect'
})
}
// 아래는 데모를 위한 UI 코드입니다.
displayToken()
function displayToken() {
const token = getCookie('authorize-access-token')
if(token) {
Kakao.Auth.setAccessToken(token)
Kakao.Auth.getStatusInfo(({ status }) => {
if(status === 'connected') {
document.getElementById('token-result').innerText = 'login success. token: ' + Kakao.Auth.getAccessToken()
} else {
Kakao.Auth.setAccessToken(null)
}
})
}
}
function getCookie(name) {
const value = "; " + document.cookie;
const parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
}
</script>
</body>
</html>
JavaScript Key에 발급받은 Java Script key를 입력해준다.
카카오 Developer → 내 애플리케이션 → 제품설정 → 카카오 로그인
redirecuri : 카카오가 redirect하는 주소
redirectUri: 'http://127.0.0.1:8000/oauth/redirect'
developer 카카오 로그인→ RedirectUri등록
https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api
import requests
from django.http import HttpResponse
from django.shortcuts import render
def kakaoLoginPage(request):
return render(request, 'login.html')
def getcode(request):
code = request.GET.get('code')
# REST API를 이용해 토큰 발급 받아옴 (카카오에게)
requests.post('https://kauth.kakao.com/oauth/token')
data = {'grant_type': "authorization_code"
, 'client_id': 'app key입력',
'redirect_uri': 'http://127.0.0.1:8000/oauth/redirect',
'code': code}
headers = {'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'}
res = requests.post('https://kauth.kakao.com/oauth/token', data=data, headers=headers)
token_json = res.json()
print(token_json)
# REST API를 이용해 토큰으로 정보를 조회
access_token = token_json['access_token']
headers = {'Authorization': 'Bearer ' + access_token,
'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'}
res = requests.get("https://kapi.kakao.com//v2/user/me", headers=headers)
profile_json = res.json()
print(profile_json)
print(profile_json['properties']['nickname']) #닉네임만 뽑아내기
return HttpResponse(code)
path('accounts/',include('allauth.urls')),
allauth로 하기 위해 카카오 로그인에서 Redirect URI를 바꿔야함(카카오 developer)http://127.0.0.1:8000/accounts/kakao/login/callback/ 로 바꾸기
관리자 계정 생성
python .\manage.py createsuperuser
'allauth.socialaccount.providers.kakao',
`{% load socialaccount %}`
`<a href="{% provider_login_url 'kakao' method='oauth2' %}">Allauth 이용한 카카오 로그인</a>`
http://127.0.0.1:8000/oauth/redirect 추가
def getCode(request):
...
user = User.objects.filter(email=kakaoid)
print('try')
if user.first() is not None:
login(request, user.first(), backend='django.contrib.auth.backends.ModelBackend')
print('if문 login')
else:
user = User()
user.email = kakaoid
user.username = profile_json['properties']['nickname']
user.save()
login(request, user.first(), backend='django.contrib.auth.backends.ModelBackend')
print('exception')
settings.py에서 django 백엔드가 충돌 가능성이 있으므로
backend='django.contrib.auth.backends.ModelBackend')
추가한다.
<에러 해결 목록>
https://ghqls0210.tistory.com/49
https://integer-ji.tistory.com/363