react-oauth/google로 구글 OAuth 로그인 구현

버건디·2023년 3월 25일
3

Next.js

목록 보기
29/52

1. react-oauth/google 설치

npm install @react-oauth/google@latest

2. GoogleOAuthProvider 로 감싸주기

"use client";

import { GoogleOAuthProvider } from "@react-oauth/google";
import SignUp from "../SignUp/SignUp";

export default function GoogleOAuth() {
  const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_KEY;

  return (
    <>
      {clientId && (
        <GoogleOAuthProvider clientId={clientId}>
          <SignUp />
        </GoogleOAuthProvider>
      )}
    </>
  );
}

3. GoogleLogin 컴포넌트불러오기

import { GoogleLogin } from '@react-oauth/google';

<GoogleLogin
  onSuccess={credentialResponse => {
    console.log(credentialResponse);
  }}
  onError={() => {
    console.log('Login Failed');
  }}
/>;

GoogleLogin 컴포넌트 자체를 불러오면

이 화면이 뜨고 로그인을 할수 있는 창이 뜬다.

- credentialResponse 값

여기서 clientId 는 google 클라우드 API 에서 발급받은 clientId 이다.

저기서 저 credential 값이 무엇인지 궁금했는데, 해당 회원정보를 담고 있는 id token이었다.

저 값을 decode 해주면 로그인한 회원의 기본 정보들이 나온다.

- decode 를 위하여 jwt-decode 설치

npm install jwt-decode
            <GoogleLogin
              onSuccess={(credentialResponse: any) => {
                console.log(jwtDecode(credentialResponse.credential));
              }}
              onError={() => {
                console.log("Login Failed");
              }}
            />

이러한 프로퍼티들을 가진 값들이 출력된다.

- aud : ID 토큰의 대상 애플리케이션에 대한 고유 식별자

- azp : ID 토큰을 사용하여 액세스 요청을 수행하는 애플리케이션에 대한 고유 식별자

- email : 이메일 주소

- email-verified : 이메일 검증이 되었는가 ?

- exp : ID 토큰 만료기간

- family-name : 사용자의 last-name

- given-name : 사용자의 first-name

- iat : ID 토큰 발급 시간

- iss : ID 토큰을 발급한 발급자의 URL 구글인 경우 accounts.google.com

- jti : ID 토큰의 고유 식별자, 일회용 토큰을 처리하는데 사용

- name : 사용자의 전체 이름

- nbf : ID 토큰이 사용되기전, 기다려야하는 시간

- picture : 사용자의 프로필 url

- sub : 사용자의 고유 식별자, 사용자가 어플리케이션에 로그인할때마다 동일하게 유지


다른 글들을 찾아봤는데, Access token을 발급 받아서 하는 경우도 있었는데, 이 경우는 로그인 후에 Google API (캘린더, 구글 드라이브 접근 등) 에 요청을 따로 보내야 할 경우에 Access token 을 발급 받으면 된다.

이 Access Token 은 GoogleLogin 컴포넌트가 아닌 useGoogleLogin 함수를 사용하면 된다.

profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글