Supabase Google 로그인 - 일반 설정
이 플러그인의 설치 단계와 전체 마크다운 가이드를 포함한 설정 지시서를 복사하세요.
Introduction
Section titled “Introduction”This guide will walk you through integrating Google Sign-In with Supabase Authentication using the Capacitor Social Login plugin. This setup allows you to use native Google Sign-In on mobile platforms while leveraging Supabase Auth for backend authentication.
Prerequisites
Section titled “Prerequisites”Before starting, ensure you have:
-
Read the Google Login General Setup guide to setup Google OAuth credentials
-
Followed the respective platform-specific guides to setup Google OAuth credentials for your target platform:
Supabase에서 Google OAuth 제공자를 활성화하는 방법
Supabase에서 Google OAuth 제공자를 활성화하는 방법-
Supabase 대시보드에 가세요 프로젝트 선택
-
프로젝트 선택
-
Do go to the
Authentication메뉴
-
Click on the
Providers탭
-
Find the
Google제공자
-
Enable the provider
-
Add the client IDs for the platforms you plan to use
-
Click on the
Savebutton
Google Sign-In with Supabase Authentication Helper의 작동 방식
Google Sign-In with Supabase Authentication Helper의 작동 방식
이 섹션은 Supabase와 Google Sign-In 통합이 어떻게 작동하는지 설명합니다. 이 흐름을 이해하면 인증 프로세스를 구현하고 문제를 해결하는 데 도움이 됩니다.완전한 Implementation
1. 난수 생성
1. 난수 생성 섹션implementation은 Supabase nonce 요구 사항을 따르는 안전한 난수 pair를 생성합니다. Supabase nonce 요구 사항:
// Generate URL-safe random noncefunction getUrlSafeNonce(): string { const array = new Uint8Array(32); crypto.getRandomValues(array); return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('');}
// Hash the nonce with SHA-256async function sha256Hash(message: string): Promise<string> { const encoder = new TextEncoder(); const data = encoder.encode(message); const hashBuffer = await crypto.subtle.digest('SHA-256', data); const hashArray = Array.from(new Uint8Array(hashBuffer)); return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');}
// Generate nonce pairasync function getNonce(): Promise<{ rawNonce: string; nonceDigest: string }> { const rawNonce = getUrlSafeNonce(); const nonceDigest = await sha256Hash(rawNonce); return { rawNonce, nonceDigest };}Flow:
rawNonce: URL-safe random string (64 hex characters)nonceDigest: SHA-256 해시의rawNonce(16진수 인코딩)nonceDigestGoogle Sign-In으로 전달되며 Google은 ID 토큰에 nonce digest를 포함합니다.rawNonceSupabase로 전달되며 Supabase는 raw nonce를 해시하고 토큰의 nonce와 비교합니다.
2. Google Sign-In
Section titled “2. Google Sign-In”함수는 플러그인을 초기화하고 Google과 로그인합니다:
await SocialLogin.initialize({ google: { webClientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', // iOS only: iOSClientId: 'YOUR_IOS_CLIENT_ID.apps.googleusercontent.com', mode: 'online', // Required to get idToken },});
const response = await SocialLogin.login({ provider: 'google', options: { scopes: ['email', 'profile'], nonce: nonceDigest, // Pass the SHA-256 hashed nonce },});3. JWT Validation
Section titled “3. JWT Validation”Supabase로 토큰을 전송하기 전에 구현은 JWT 토큰을 검증합니다:
function validateJWTToken(idToken: string, expectedNonceDigest: string): { valid: boolean; error?: string } { const decodedToken = decodeJWT(idToken);
// Check audience matches your Google Client IDs const audience = decodedToken.aud; if (!VALID_GOOGLE_CLIENT_IDS.includes(audience)) { return { valid: false, error: 'Invalid audience' }; }
// Check nonce matches const tokenNonce = decodedToken.nonce; if (tokenNonce && tokenNonce !== expectedNonceDigest) { return { valid: false, error: 'Nonce mismatch' }; }
return { valid: true };}왜 Supabase 전에 검증할까요?
Supabase로 토큰을 전송하기 전에 JWT 토큰을 검증하는 것은 여러 중요한 목적을 위해 사용됩니다:
-
Invalid한 요청 방지: 토큰이 잘못된 청중 또는 nonce 일치하지 않으면 Supabase는 토큰을 거부하겠지만, 먼저 검증하면 불필요한 API 호출을 피하고 더 명확한 오류 메시지를 제공합니다.
-
토큰 캐싱 문제: iOS에서 Google Sign-In SDK은 성능을 위해 토큰을 캐싱할 수 있습니다. 캐시된 토큰이 반환될 때, 캐시된 토큰이 다른 nonce (혹은 nonce가 없는 경우)로 생성되었을 수 있습니다. 이로 인해 Supabase가 nonce 일치 오류를 반환합니다. Supabase로 전송하기 전에 토큰을 검증하면 이 문제를 일찍 감지하고 자동으로 다시 시도할 수 있습니다.
-
보안 (iOS): iOS에서, validation은 특정 Google Client IDs에 발급된 토큰만 허용하여, 다른 애플리케이션의 토큰을 사용하는 잠재적인 보안 문제를 방지합니다.
-
오류 처리: Supabase로 전송하기 전에 토큰을 검증하면 iOS 캐싱 문제를 투명하게 자동으로 다시 시도할 수 있습니다.
검증이 실패하면 함수는 자동으로:
- Google에서 로그아웃 (iOS에서 캐시된 토큰을 삭제 - 중요)
- 인증을 다시 시도 (새로운 토큰 생성을 강제)
- 재시도가 실패하면 오류를 반환
4. Supabase Sign-In
제목 ‘4. Supabase Sign-In’마지막으로, 검증된 토큰이 Supabase로 전송됩니다.
const { data, error } = await supabase.auth.signInWithIdToken({ provider: 'google', token: googleResponse.idToken, nonce: rawNonce, // Pass the raw (unhashed) nonce});Complete Code Reference
Complete Code Reference예제 앱의 파일에서 완전한 implementation을 확인할 수 있습니다. 이 파일에는 다음과 같은 기능이 포함되어 있습니다. supabaseAuthUtils.ts - URL-safe random nonce을 생성합니다.
getUrlSafeNonce()- SHA-256 해시 함수를 사용하여 문자열을 해시합니다.sha256Hash()- nonce pair을 생성합니다.getNonce()- JWT 토큰을 디코딩합니다.decodeJWT()- JWT 토큰의 audience와 nonce을 검증합니다.validateJWTToken()- 자동 재시도 기능이 포함된 메인 인증 함수authenticateWithGoogleSupabase()__CAPGO_KEEP_0__
추가 예제 파일
추가 예제 파일 섹션 제목- SupabasePage.tsx - 웹에서 리다이렉트 처리를 하는 예제 컴포넌트
- SupabaseCreateAccountPage.tsx - 계정 생성 페이지 예제
다음 단계
다음 단계 섹션 제목다음 단계는 대상 플랫폼에 대한 플랫폼별 설정 가이드로 진행해 주세요.
Supabase Google 로그인 - 일반 설정에서 계속
‘Supabase Google 로그인 - 일반 설정에서 계속’ 제목Supabase Google 로그인 - 일반 설정에서 계속하는 경우 Supabase Google 로그인 - 일반 설정 인증 및 계정 흐름을 계획하고 연결하려면 @capgo/capacitor-social-login을 사용하여 @capgo/capacitor-social-login의 원시 기능을 사용하여 @capgo/capacitor-social-login @capgo/capacitor-passkey @capgo/capacitor-passkey의 구현 세부 정보 @capgo/capacitor-native-biometric 인증 및 계정 흐름을 계획하고 연결하려면 @capgo/capacitor-social-login을 사용하십시오. @capgo/capacitor-native-biometric, and 두 단계 인증 @__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-native-biometric.