Supabase Google 로그인 - 일반 설정
이 플러그인을 설치하는 데 필요한 단계와 이 플러그인의 전체 마크다운 가이드를 포함한 설정 프롬프트를 복사합니다.
소개
소개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.
사전 요구 사항
기본 요구 사항시작하기 전에 다음을 확인하세요.
-
스타일 가이드를 읽어보세요 Google Login 일반 설정 Google OAuth 인증서를 설정하는 방법을 알아보세요.
-
Google OAuth 인증서를 설정하는 방법을 알아보세요.
Supabase에서 Google OAuth 제공자를 활성화하는 방법
Supabase에서 Google OAuth 제공자를 활성화하는 방법-
Supabase 대시보드 프로젝트
-
프로젝트 선택기
-
인증 메뉴
Authentication탭
-
선택
Providers선택
-
찾아보세요
Google제공자
-
제공자를 활성화하세요
-
사용할 플랫폼에 따라 클라이언트 ID를 추가하세요
-
클릭하세요
Save버튼
Voilà, 이제 Supabase 인증과 함께 Google Sign-In을 활성화했습니다 🎉
Supabase 인증과 함께 Google Sign-In Helper가 어떻게 작동하는지
구글 시그니인과 Supabase 인증 도우미의 작동 방식이 섹션에서는 Supabase와 구글 시그니인 통합의 내부 작동 방식을 설명합니다. 이 흐름을 이해하면 인증 프로세스를 구현하고 문제를 해결하는 데 도움이 됩니다.
1. 난수 생성
1. 비공개 토큰 생성// 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 문자열 (64 개의 16진수 문자)nonceDigest: SHA-256 해시의rawNonce(16진수 인코딩)nonceDigest는 Google Sign-In으로 전달 → Google은 ID 토큰에 nonce의_DIGEST를 포함합니다.rawNonce는 Supabase로 전달 → Supabase는 raw nonce를 해시하고 토큰의 nonce와 비교합니다.
2. 구글 시그니인
제목이 "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 인증 검증
제목이 "3. JWT Validation"인 섹션Supabase 토큰을 전송하기 전에 implementation은 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 토큰을 검증하는 것은 여러 중요한 목적을 위해 사용됩니다:
-
잘못된 요청 방지: 토큰의 오류가 있는 청중 또는 nonce 불일치가 있는 경우 Supabase는 토큰을 거부하더라도 토큰을 검증하는 것은 불필요한 API 호출을 피하고 더 명확한 오류 메시지를 제공합니다.
-
토큰 캐싱 문제: iOS와 같은 일부 플랫폼 (특히 iOS)에서 Google Sign-In SDK가 성능을 위해 토큰을 캐싱할 수 있습니다. 캐시된 토큰이 반환될 때 캐시된 토큰은 이전에 생성된 nonce (또는 nonce가 없는 경우)와 다를 수 있습니다. 따라서 Supabase는 nonce 불일치 오류로 토큰을 거부합니다. Supabase로 토큰을 전송하기 전에 검증하면 이 문제를 일찍 감지하고 자동으로 새 토큰으로 다시 시도할 수 있습니다.
-
보안 컨텍스트: Enterprise 제품/가격 페이지. 역할: UI 레이블. 표시되는 곳: enterprise.astro 페이지. 메시지 키 `enterprise_hero_security_label` (Enterprise Hero Security Label).
-
(iOS): iOS에서 검증은 특정 Google Client IDs를 위한 토큰이 발급되었는지 확인하여 다른 애플리케이션의 토큰을 사용하는 잠재적인 보안 문제를 방지합니다.오류 처리 향상
유효성 검사 실패 시 함수는 자동으로:
- 구글에서 로그아웃 (iOS에서 캐시된 토큰 삭제 - iOS에서 매우 중요)
- 인증을 다시 시도 (새로운 토큰 생성을 강제하고 올바른 nonce 사용)
- 재시도도 실패하면 오류를 반환
4. Supabase 로그인
제목 "4. Supabase 로그인"유효성 검사된 토큰이 최종적으로 Supabase로 전송됩니다:
const { data, error } = await supabase.auth.signInWithIdToken({ provider: 'google', token: googleResponse.idToken, nonce: rawNonce, // Pass the raw (unhashed) nonce});완전한 Code 참조
제목 "완전한 Code 참조"완전한 구현은 예제 앱의 예제 앱의 supabaseAuthUtils.ts 파일, 이에 포함되어 있습니다:
getUrlSafeNonce()- URL-safe 난수 생성sha256Hash()- SHA-256로 문자열 해시getNonce()- 난수 pair 생성decodeJWT()- JWT 토큰 디코딩validateJWTToken()- JWT 청중과 난수 유효성 검사authenticateWithGoogleSupabase()- 자동 재시도 포함된 인증 함수
추가 예제 파일
제목 ‘추가 예제 파일’- SupabasePage.tsx - 웹에서 리다이렉트 처리를 포함한 예제 컴포넌트
- SupabaseCreateAccountPage.tsx - 계정 만들기 예시 페이지
다음 단계
페이지 제목: 다음 단계다음 단계를 위해 플랫폼에 따라 설정 가이드를 참조하십시오.
Supabase Google Login - 일반 설정에서 계속 진행하십시오.
페이지 제목: Supabase Google Login - 일반 설정에서 계속Supabase Google Login - 일반 설정을 사용하여 인증 및 계정 흐름을 계획하고 그것을 인증 및 계정 흐름을 계획하고 연결하려면 @capgo/capacitor-social-login for the native capability in Using @capgo/capacitor-social-login @capgo/capacitor-social-login for the implementation detail in @capgo/capacitor-social-login @capgo/capacitor-passkey for the implementation detail in @capgo/capacitor-passkey @capgo/capacitor-native-biometric for the implementation detail in @capgo/capacitor-native-biometric, and 두 요인 인증 구글 소셜 로그인 플러그인에서 두 단계 인증 구현 세부 사항을 참조하세요.