跳过内容

在 Web 上使用 Supabase 进行 Google 登录

本指南将帮助您在 Web 上将 Google Sign-In 与 Supabase 身份验证集成。假设您已经完成:

完整的实施可在 文件中找到。 本指南解释了关键概念和如何使用它。 supabaseAuthUtils.ts 使用身份验证助手

复制到剪贴板 authenticateWithGoogleSupabase 警告:重定向处理

import { authenticateWithGoogleSupabase } from './supabaseAuthUtils';
const result = await authenticateWithGoogleSupabase();
if (result.success) {
console.log('Signed in:', result.user);
// Navigate to your authenticated area
} else {
console.error('Error:', result.error);
}

__CAPGO_KEEP_0__

__CAPGO_KEEP_0__

__CAPGO_KEEP_0__

使用 Google 登录时,web 端需要 __CAPGO_KEEP_0__ 当发生重定向时,必须调用插件中的任何函数来初始化插件,以便它可以处理重定向并关闭弹出窗口。您可以调用 isLoggedIn() __CAPGO_KEEP_1__ initialize() -

两者都会触发重定向处理。

此步骤对于 OAuth 弹出窗口流程的正常工作至关重要。

实现示例

标题:实现示例

import { useEffect } from 'react';
import { SocialLogin } from '@capgo/capacitor-social-login';
function SupabasePage() {
// Check Google login status on mount to invoke redirect handling
// This doesn't serve any functional purpose in the UI but ensures
// that any pending OAuth redirects are properly processed
useEffect(() => {
const checkGoogleLoginStatus = async () => {
try {
await SocialLogin.isLoggedIn({ provider: 'google' });
// We don't use the result, this is just to trigger redirect handling
} catch (error) {
// Ignore errors - this is just for redirect handling
console.log('Google login status check completed (redirect handling)');
}
};
checkGoogleLoginStatus();
}, []);
// ... rest of your component
}

复制到剪贴板 查看 完整示例。

有关如何工作的详细说明,包括 nonce 生成、 JWT 验证和 Supabase 登录,请参见 如何工作部分在 General Setup 指南中.

有关完整的 code 参考,请参见 完整的 Code 参考部分在 General Setup 指南中.

另外,请参见:

注意事项

重要注意事项

重定向处理

重定向处理

在使用 Google 登录时, 必须 当发生重定向时, isLoggedIn()initialize() 这对于 OAuth popup 流程的正常工作至关重要。如果没有这个步骤,认证后弹出窗口不会关闭。

随机数处理

随机数处理

重定向处理

The nonce implementation follows the pattern from the React Native Google Sign In 文档:

  • rawNonce 去到 Supabase 的 signInWithIdToken()
  • Supabase 生成一个 rawNonce 并与 nonceDigest 从 Google Sign-In 中的
  • nonceDigest (SHA-256 hash, hex-encoded) 传递到 nonce 参数在 Google Sign-In APIs

实现包括自动重试逻辑:

  • 如果 JWT 验证在第一次尝试失败,它会注销并重试一次
  • 处理缓存令牌可能有错误的 nonce 的情况
  • 如果重试也失败,则返回错误

如果认证失败:

  • 重定向不起作用: 确保您在组件挂载时调用 isLoggedIn() 非法受众
  • : 验证您的 Google Client IDs 是否在 Google Cloud Console 和 Supabase 中都匹配已授权重定向 URL
  • : 检查是否在 Google Cloud Console 和 Supabase 中都配置了已授权的重定向 URL: 检查您是否正确配置了已授权的重定向 URL
  • 令牌不匹配: 检查控制台日志 - 函数将自动重试,但如果需要,可以手动注销
  • 令牌验证失败: 确保在初始化调用中使用 mode: 'online' 查看
  • 示例应用 __CAPGO_KEEP_0__ example app code 编辑页面