Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

NodeJS - KAKAO LOGIN (추가) 본문

NodeJS

NodeJS - KAKAO LOGIN (추가)

보람- 2023. 10. 26. 18:13

목차

1. 인가코드 받기

2. 토큰 받기

3. 사용자 정보 가져오기


 

 

 

 

 

 

 

1. 인가코드 받기

GET https://kauth.kakao.com/oauth/authorize?client_id=값&redirect_uri=값&response_type=값
app.get("/auth/kakao/login", (req, res, next) => {
    try {
        const redirectURI = `https://kauth.kakao.com/oauth/authorize?client_id=${REST_API_KEY}&redirect_uri=${KAKAO_REDIRECT_URI}&response_type=code`;
        res.redirect(redirectURI);
    } catch (e) {
        next(e);
    }
});

- 카카오 로그인으로 '로그인' 하겠다고 요청했을때  카카오서버로 가라고 redirect 되고

- 카카오 서버에 로그인하겠다고 하면 아이디, 비밀번호 입력하는 화면을 응답해주고

- 아이디 비밀번호 입력하고 보내면 카카오서버에서 로그인 성공하면 받을 redirect uri로 REDIRECT해주면서 인가코드를 준다.

 

{
  code: 'codecodcodcodcodcodeeecodeecodee'
}

- 코드로 주는것이 OAuth 2.0 의 프로토콜이라고한다.

  - 바로 토큰으로 주지않고 휘발되는 코드로 주어서 보안상의 문제 해결(탈취위험성 등등)

 

- 동의 항목 체크도 했다면

 

 

 

 

2. 토큰 받기

 

- 요청하기

POST https://kauth.kakao.com/oauth/token

- header
   - Content-type: application/x-www-form-urlencoded;charset=utf-8 요청 데이터 타입

- body
   - grant_type : String authorization_code로 고정
   - client_id : String 앱 REST API 키 [내 애플리케이션] > [앱 키]에서 확인 가능
   - redirect_uri : String 인가 코드가 리다이렉트된 URI
   - code : String 인가 코드 받기 요청으로 얻은 인가 코드

 

 

app.get("/auth/kakao/callback", async (req, res, next) => {
    try {
        const {code} = req.query;
        const host = "https://kauth.kakao.com/oauth/token";
        const body = `grant_type=authorization_code&client_id=${REST_API_KEY}&redirect_uri=${KAKAO_REDIRECT_URI}&code=${code}`;
        const respones = await axios.post(host, body, {
            "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
        });
        console.log(respones);
        res.send();
    } catch (e) {
        next(e);
    }
});

- redirect uri 주소였던 /auth/kakao/callback 으로 다시 요청을 보내는데

- 이걸 받은 프론트 서버는 카카오서버에 요청으로 받았던 인가코드와 함께 토큰을 달라고 요청한다.

- 요청받은 카카오서버는 코드확인을하고 맞다면 access-token을 응답해준다.

 

data: {
    access_token: 'acaccess_tokenceaccess_tokenssaccess_token_token',
    token_type: 'bearer',
    refresh_token: 'refrrefresh_tokenesh_tokrrefresh_tokenefresh_tokenen',
    expires_in: 21599,
    refresh_token_expires_in: 5183999
}

 

 

 

 

3. 사용자 정보 가져오기

 

- access token을 받았다면 한번더 요청을 보내야한다.

GET https://kapi.kakao.com/v2/user/me

- 요청한 사람이 나임을 증명할수있게 header에 Authorization: 에 access token을 넣어서 요청을 보낸다!

 

const { data: {access_token} } = respones;
console.log(access_token);

const userinfo = await axios.get("https://kapi.kakao.com/v2/user/me", {
    headers: {
        "Content-type":
            "application/x-www-form-urlencoded;charset=utf-8",
        Authorization: `Bearer ${access_token}`,
    },
});
console.log(userinfo);
 data: {
    id: ------------,
    connected_at: '2023-10-26T04:20:28Z',
    properties: {
      nickname: '보람',
      profile_image: 'http://k.kakaocdn.net/dn/bV1hlA/btswcLS7HUm/img_640x640.jpg',
      thumbnail_image: 'http://k.kakaocdn.net/dn/bV1hlA/btswcLS7HUm/img_110x110.jpg'
    },

 

 

※ 추가로 작업할내용

- 받은 데이터로 필요한 항목 뽑아서 백엔드 서버에 TOKEN 요청하고 

- 백엔드는 DB에 SELECT 해본 후 없는 회원이면 INSERT 하고, 프론트서버에 TOKEN을 응답

- 프론트는 받은 토큰을 가지고 SET-COOKIE, redirect로 메인페이지이동을 응답

- 브라우저는 쿠키 여부로 화면을 다르게 보여주기

 

※ 완성 코드 github

https://github.com/kimboram22/kakao_login

 

 

 


※ 공식문서 

https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

 

 

'NodeJS' 카테고리의 다른 글

NodeJS - WebSocket, CHAT  (1) 2023.10.31
NodeJS - File Upload  (0) 2023.10.30
NodeJS - TDD  (0) 2023.10.25
NodeJS - DTO  (0) 2023.10.24
NodeJS - ORM, Sequelize, User CRUD  (1) 2023.10.23