__CAPGO_KEEP_0__ - __CAPGO_KEEP_1__ 앱의 실시간 업데이트

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.

Before starting, ensure you have:

  1. Created a Supabase project

  2. Read the Google Login General Setup guide to setup Google OAuth credentials

  3. Followed the respective platform-specific guides to setup Google OAuth credentials for your target platform:

Supabase에서 Google OAuth 제공자를 활성화하는 방법

Supabase에서 Google OAuth 제공자를 활성화하는 방법
  1. Supabase 대시보드에 가세요 프로젝트 선택

  2. 프로젝트 선택

    Capgo
  3. Do go to the Authentication 메뉴

    Supabase 인증 메뉴
  4. Click on the Providers

    Supabase 제공자 탭
  5. Find the Google 제공자

    Supabase Google 제공자
  6. Enable the provider

    Supabase Google 제공자 활성화
  7. Add the client IDs for the platforms you plan to use

    Supabase Google Provider Add Client IDs
  8. Click on the Save button

    Supabase Google Provider Save

Google Sign-In with Supabase Authentication Helper의 작동 방식

완전한 Implementation

1. 난수 생성

1. 난수 생성 섹션

implementation은 Supabase nonce 요구 사항을 따르는 안전한 난수 pair를 생성합니다. Supabase nonce 요구 사항:

// Generate URL-safe random nonce
function 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-256
async 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 pair
async 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진수 인코딩)
  • nonceDigest Google Sign-In으로 전달되며 Google은 ID 토큰에 nonce digest를 포함합니다.
  • rawNonce Supabase로 전달되며 Supabase는 raw nonce를 해시하고 토큰의 nonce와 비교합니다.

함수는 플러그인을 초기화하고 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
},
});

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 토큰을 검증하는 것은 여러 중요한 목적을 위해 사용됩니다:

  1. Invalid한 요청 방지: 토큰이 잘못된 청중 또는 nonce 일치하지 않으면 Supabase는 토큰을 거부하겠지만, 먼저 검증하면 불필요한 API 호출을 피하고 더 명확한 오류 메시지를 제공합니다.

  2. 토큰 캐싱 문제: iOS에서 Google Sign-In SDK은 성능을 위해 토큰을 캐싱할 수 있습니다. 캐시된 토큰이 반환될 때, 캐시된 토큰이 다른 nonce (혹은 nonce가 없는 경우)로 생성되었을 수 있습니다. 이로 인해 Supabase가 nonce 일치 오류를 반환합니다. Supabase로 전송하기 전에 토큰을 검증하면 이 문제를 일찍 감지하고 자동으로 다시 시도할 수 있습니다.

  3. 보안 (iOS): iOS에서, validation은 특정 Google Client IDs에 발급된 토큰만 허용하여, 다른 애플리케이션의 토큰을 사용하는 잠재적인 보안 문제를 방지합니다.

  4. 오류 처리: Supabase로 전송하기 전에 토큰을 검증하면 iOS 캐싱 문제를 투명하게 자동으로 다시 시도할 수 있습니다.

검증이 실패하면 함수는 자동으로:

  1. Google에서 로그아웃 (iOS에서 캐시된 토큰을 삭제 - 중요)
  2. 인증을 다시 시도 (새로운 토큰 생성을 강제)
  3. 재시도가 실패하면 오류를 반환

마지막으로, 검증된 토큰이 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__

다음 단계는 대상 플랫폼에 대한 플랫폼별 설정 가이드로 진행해 주세요.

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.