반응형
npm
npm install @react-oauth/google
npm install jwt-decode
구글 API OAuth 사용자 인증 정보
내부 타입으로 할 경우 직접 선택한 유저만 사용 가능하고, 외부 타입으로 할 경우 모든 사용자가 사용 가능합니다.
Client ID와 Client Secret ID는 잘 저장해둡니다.
앱 게시를 하게되면 이전에 외부 타입으로 설정하는 것과 같습니다. ( 현재는 내부로 했기 때문에 이런식으로 표현되며, 다시 테스트로 돌아갈 수도 있습니다. )
테스트로 사용할 경우 아래 테스트 사용자를 추가할 수 있습니다. ( 추가된 사용자만 사용이 가능해집니다. )
.env.development ( 최상위 경로 src 상위 )
REACT_APP_CLIENT_ID = "클라이언트 아이디 ( 위에서 생성한 아이디 )"
react-app-env.d.ts ( 최상위 경로에 있는 파일 )
/// <reference types="react-scripts" />
declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: 'development' | 'production' | 'test';
readonly PUBLIC_URL: string;
REACT_APP_CLIENT_ID: string;
}
}
위 코드처럼 작성하면 REACT_APP_CLIENT_ID를 자동완성 시킬수 있습니다. ( 타입 지정 이라고 생각하면 편합니다. )
App.tsx
import { CredentialResponse, GoogleLogin, GoogleOAuthProvider } from "@react-oauth/google";
import jwtDecode from "jwt-decode";
interface GoogleDecodedProps {
aud: string,
azp: string,
email: string,
email_varified: boolean,
exp: number,
family_name: string,
given_name: string,
iat: number,
iss: string,
jti: string,
name: string,
nbf: number,
picture: string,
sub: string
}
export const App = () => {
// 구글 클라이언트 아이디 정보
const configValue = process.env.REACT_APP_CLIENT_ID;
const onGoogleLogin = async (res: CredentialResponse) => {
const decoded: GoogleDecodedProps = jwtDecode(JSON.stringify(res));
console.log(decoded);
}
return (
<article>
<button className={styles.button_color_google}>
<GoogleOAuthProvider clientId={configValue}>
<GoogleLogin onSuccess={credentialResponse => {onGoogleLogin(credentialResponse)}} onError={() => console.log("ERR")}></GoogleLogin>
</GoogleOAuthProvider>
</button>
</article>
)
}
jwtDecode()로 해독해주면 위 interface 내용과 같이 사용자 정보가 나오게 됩니다.
반응형
'React > React' 카테고리의 다른 글
[ React ] Redux Toolkit 연습하기 ( 1 ) (0) | 2023.01.26 |
---|---|
[ React ] React CRUD ( Feat. Typescript ) (0) | 2023.01.11 |
[ React ] IntrinsicAttributes & AuthProps Error (0) | 2022.12.21 |
[ React ] redux 데이터 스토리지에 저장하기 ( redux-persist ) (0) | 2022.11.29 |
[ React ] socket io 사용하기 (0) | 2022.11.18 |