카테고리 없음

google 소셜 로그인할 때 소셜 로그인한 유저 정보 가져오기

nickbegain 2021. 7. 28. 16:57

require('dotenv').config();

const clientID = process.env.GOOGLE_CLIENT_ID;

const clientSecret = process.env.GOOGLE_CLIENT_SECRET;

const axios = require("axios")

 

module.exports = {

google : (req, res) => {

// 아래 api주소와 payload값을 이용해서 클라이언트로 부터 소셜로그인 시도로 받은 authorization code를 해당 api로 전달하여 access_token을 가져온다.

axios.post(`https://oauth2.googleapis.com/token`,{

client_id: clientID,

client_secret: clientSecret,

code: req.body.authorizationCode,

grant_type : 'authorization_code',

redirect_uri : "https://localhost:3000"

})

.then(response => {

 

let params = new URLSearchParams(response.data);

let accessToken = params.get("access_token")

console.log(accessToken);

// 아래 api주소로 query 파라미터에 전달받은 access 토큰을 전달하면 해당 유저의 정보를 가져올수 있다.

axios.get(`https://www.googleapis.com/oauth2/v2/userinfo?access_token=${accessToken}`,

{ withCredentials: true })

.then((response) => {

console.log(response.data);

})

// response.data 출력결과 

{
  id: '113198665486717304194',
  name: '정승환',
  given_name: '승환',
  family_name: '정',
  picture: 'https://lh3.googleusercontent.com/a/AATXAJwbCthAKefGXvnG82Ff4rebGHXtJWZZJt62Ua0R=s96-c',
  locale: 'ko'
}

 

})

}

}