❗️Error/오류를 해결하자!

구글 소셜 로그인 프론트단에서 토큰까지 발급 받기 (OAuth2.0)

hellohailie 2022. 10. 11. 17:26

 

이번 포스팅은 프론트단에서 구글 소셜로그인으로 토큰까지 발급받을 수 있는 방법에 대해 정리한 글입니다. 

 

1. 구글 API 등록하기

https://console.cloud.google.com/apis/dashboard

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

 

1-1. [사용자 인증 정보] 탭에서 승인된 자바스크립트 원본과 승인된 리디엑션 URI을 적습니다. 

(주의! 127.0.0.1 은 오류가 나므로 localhost로 적습니다. )

 

1-2. [OAuth 동의 화면] 탭에서 게시 상태, 사용자 유형(외부), 테스트 사용자(테스트할 이메일) 적습니다. 

 

 

 

 


구글 클라이언트 아이디는 secretData.js라는 파일에 따로 보관하여 github에는 올라가지 않도록 주의하도록 합니다. 

 

구글 버튼은 react-google-login 라는 라이브러리를 사용했다.

(npm i react-google-login 로는 설치가 되지 않아서 force로 설치했습니다. )

import GoogleLogin from "react-google-login";

 

구글 버튼 css

  .googleBtn {
      margin: 0px 0px;
      width: 48px;
      height: 48px;
      border-radius: 100% !important;

      & div {
        width: 48px;
        height: 48px;
        border-radius: 100% !important;

        & svg {
          margin: 5px 1px 0px 5px;
        }
      }
    }

 

코드상 버튼 부분

<GoogleLogin
className='googleBtn'
 clientId={GOOGLE_CLIENT_ID}
buttonText=''
onSuccess={onSuccess}
 onFailure={onFailure}
/>

 

버튼과 연결되어있는 코드

추가적으로  라이브러리를 설치해서 사용했습니다. 

import { gapi } from "gapi-script";
 useEffect(() => {
    function start() {
      gapi.auth2.init({
        clientId: GOOGLE_CLIENT_ID,
        scope: "email",
      });
    }
    gapi.load("client:auth2", start);
  }, []);

  const onSuccess = (res) => {
    const profile = res.getBasicProfile();
    const userdata = {
      email: profile.getEmail(),
      image: profile.getImageUrl(),
      name: profile.getName(),
    };
    // 로그인 성공 후 실행하기 원하는 코드 작성.
    sessionStorage.setItem("g_access_token", res.accessToken);
    axios({
      method: "post",
      url: `백엔드 구글 엔드포인트추가`,
      data: res.accessToken,
    });
    navigate("/puppyauthentication");
  };

  const onFailure = (res) => {
    Swal.fire({
      icon: "warning",
      text: "구글 로그인에 실패하였습니다",
      width: "400px",
    });
    console.log("err", res);
  };

 

 

 

⚠️저는 로컬 환경에서 테스트했기 때문에 배포환경에서는 위 코드에서 추가적인 설정이 필요할 수 있습니다. ⚠️

 

 

😃 잘못된 개념 전달이 있다면 댓글 부탁드립니다. 저의 성장에 큰 도움이 됩니다🤓