github 말고 kakao로도 로그인 해보자. github와 용어만 다를 뿐 흐름은 똑같다.
✅ kakao도 이와 동일한 흐름을 가진다.
export const kakaoLogin = (req, res) => {
const base_url = "https://kauth.kakao.com/oauth/authorize";
const config = {
client_id: process.env.KAKAO_CLIENT_ID,
redirect_uri: "http://localhost:4000/users/kakao/callback",
response_type: "code",
};
const config_url = new URLSearchParams(config).toString();
const final_url = `${base_url}?${config_url}`;
return res.redirect(final_url);
};
kakao에서 client_id는 REST API id값이다.
성공하면 카카오에서 code를 준다.
export const kakaoCallback = async (req, res) => {
const base_url = "https://kauth.kakao.com/oauth/token";
const config = {
grant_type: "authorization_code",
client_id: process.env.KAKAO_CLIENT_ID,
redirect_uri: "http://localhost:4000/users/kakao/callback",
code: req.query.code,
client_secret: process.env.KAKAO_CLIENT_SECRET,
};
const config_url = new URLSearchParams(config).toString();
const final_url = `${base_url}?${config_url}`;
const tokenRequest = await (
await fetch(final_url, {
method: "POST",
headers: {
"Content-type": "apllication/json",
},
})
).json();
console.log(tokenRequest);
}
▶ 출력값 ( json )
{
access_token: 'Y8PHQYJKL9ewnrAt3T9tvsw85TJ_E4tUt3lo3Ao9dJkAAAF6mupe3g',
token_type: 'bearer',
refresh_token: 'slgKCjAWfXdb-DDhY8EVlJiLHePN1GMcqVqKZQo9dJkAAAF6mupe3Q',
expires_in: 21599,
scope: 'account_email profile_image profile_nickname story_permalink',
refresh_token_expires_in: 5183999
}
export const kakaoCallback = async (req, res) => {
...
if ("access_token" in tokenRequest) {
const { access_token } = tokenRequest;
const userData = await (
await fetch("https://kapi.kakao.com/v2/user/me", {
headers: {
Authorization: `Bearer ${access_token}`,
"Content-type": "application/json",
},
})
).json();
console.log(userData);
...
};
▶ 출력값 ( json )
{
id: 1123456678,
...
kakao_account: {
profile_nickname_needs_agreement: false,
profile_image_needs_agreement: false,
profile: {
nickname: 'abc',
thumbnail_image_url: '비밀',
profile_image_url: '비밀',
is_default_image: false
},
has_email: true,
email_needs_agreement: false,
is_email_valid: true,
is_email_verified: true,
email: 'abc@naver.com',
has_birthday: false,
birthday_needs_agreement: false,
has_gender: false,
gender_needs_agreement: false
}
}
kakao는 사업자 정보를 등록해야 email을 "필수 동의" 할 수 있다. 이 점이 매우 불편하다.
따로 kakao에 유저 정보를 요구하는 "scope" 이 없다. 동의항목에 체크하는 것이 scope을 대신한다.