<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>OAuth 실습</h1>
<button id="kakao">카카오 로그인</button>
<button id="naver">네이버 로그인</button>
<main>
<img />
<div>유저 이름 : <span id="user_name"></span></div>
<button id="logout_button">로그아웃</button>
</main>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="login.js"></script>
</body>
</html>
body {
padding: 0 20px;
}
main {
border: 1px solid gray;
border-radius: 10px;
padding: 20px;
margin-top: 20px;
width: 200px;
display: grid;
place-items: center;
}
div {
margin-bottom: 20px;
}
button {
padding: 10px 20px;
margin-right: 6px;
}
#logout_button {
width: 100%;
height: 50px;
}
img {
width: 100px;
height: 100px;
background-color: gray;
border-radius: 100%;
margin-bottom: 10px;
object-fit: cover;
}
npm init -y
npm install express cors axios
{
"name": "oauth",
"version": "1.0.0",
"main": "login.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"axios": "^1.7.4",
"cors": "^2.8.5",
"express": "^4.19.2"
}
}
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(cors({
origin: ["http://127.0.0.1:5500", "http://localhost.1:5500"],
//로그인할 때 사용할 POST와 로그아웃할 때 사용할 DELETE
methods: ["OPTIONS", "POST", "DELETE"],
// 데이터를 쿠키로 주고받을 경우에는 credentials 설정 필요
}))
app.use(express.json());
app.listen(port, callback)
port
: 서버가 실행될 포트 번호callback
: 서버가 정상적으로 실행되었을 때 실행되는 콜백 함수app.listen(3000, () => console.log('3000번 포트에서 서버 열림'))
const kakaoLoginButton = document.querySelector("#kakao");
const naverLoginButton = document.querySelector("#naver");
const userImage = document.querySelector("img");
const userName = document.querySelector("#user_name");
const logoutButton = document.querySelector("#logout_button");
const kakaoClientId = 'd14c29937265b0e48b1765ee823da865'
const kakaoClientId = [발급받은 Client ID]
const redirectURI = 'http://127.0.0.1:5500'
kakaoLoginButton.onclick = () => {
// 화면을 호출하기 위한 이동 코드
location.href = `https://kauth.kakao.com/oauth/authorize?client_id=${kakaoClientId}&redirect_uri=${redirectURI}&response_type=code`
}
window.onload = () => {
// 현재 페이지의 URL을 가져옴
const url = new URL(location.href);
const urlParams = url.searchParams;
// 카카오가 리디렉트하면서 URL에 추가한 'code' 값을 가져옴
const authorizationCode = urlParams.get('code');
console.log(authorizationCode);
};
app.post('/kakao/login', (req, res) => {
const authorizationCode = req.body.authorizationCode;
axios.post('https://kauth.kakao.com/oauth/token', {
grant_type : 'authorization_code',
client_id : kakaoClientId,
redirect_uri : redirectURI,
code : authorizationCode
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(response => res.send(response.data.access_token))
})
axios.post('http://localhost:3000/kakao/login', {
authorizationCode})
.then(res => {
kakaoAccessToken = res.data;
return axios.post('http://localhost:3000/kakao/userinfo', {kakaoAccessToken})
})
.then(res => {
console.log(res.data)
const userInfo = res.data
renderUserInfo(userInfo.profile_image, userInfo.nickname)
});
}
app.post('/kakao/userinfo', (req, res) => {
const {kakaoAccessToken} = req.body;
axios.get('https://kapi.kakao.com/v2/user/me', {
headers : {
Authorization : `Bearer ${kakaoAccessToken}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(response => {
console.log(response.data.properties)
res.send(response.data.properties)
})
})
logoutButton.onclick = () => {
axios.delete('http://localhost:3000/kakao/logout', {
data : {kakaoAccessToken}
}).then(res => {
console.log(res.data)
renderUserInfo('', '')
})
}
app.delete('/kakao/logout', (req, res) => {
const {kakaoAccessToken} = req.body
console.log(kakaoAccessToken)
axios.post('https://kapi.kakao.com/v1/user/logout', {} ,{
headers : {
Authorization : `Bearer ${kakaoAccessToken}`,
}}).then(response => res.send('로그아웃 성공!'))
})