
Supabase Auth 怎么为移动端 App 配置 Deep Linking 以处理 Magic Link 与 OAuth 回调【免费下载链接】supabaseThe Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.项目地址: https://gitcode.com/GitHub_Trending/supa/supabase在移动端 App 里使用 Supabase Auth 时Magic Link 登录、邮箱注册确认、密码重置邮件以及第三方 OAuth 登录都会产生一次“跳回你的 App”的重定向邮件里的链接指向你的 AppOAuth 完成后也会自动跳回 App。如果 App 没有注册对应的自定义 URL Scheme 并处理回跳的 URL用户点击链接后无法回到 App登录流程就断在半路。这篇文章基于仓库中 Native Mobile Deep Linking 文档说明如何为移动端 App 配置 Deep Linking让 Magic Link 与 OAuth 回调能够正确回到 App 并建立会话覆盖 Expo React Native、FlutterAndroid/iOS、SwiftiOS与 Android Kotlin 四种平台。配置流程的三个阶段无论使用哪个平台 SDK文档中的配置都包含相同的三个阶段在 Supabase 项目的 Auth 设置中登记回调 URL打开 Supabase 控制台的 Auth settingsURL Configuration 页面在Additional Redirect URLs字段填入 App 的回调地址格式为[YOUR_SCHEME]://[YOUR_HOSTNAME]。Scheme 在用户的设备上必须唯一文档建议通常使用你网站域名的反向域名作为 scheme。例如文档给出的示例是io.supabase.flutterquickstart://login-callback。在 App 中注册该 URL Scheme让操作系统知道这个 scheme 应该打开你的 App。在代码中处理回跳的 URL把收到的 URL 交给 Supabase 客户端完成会话建立。控制台中的回调地址配置界面如下截图来自文档主路径Expo React NativeExpo React Native 是文档默认展示的平台也是示例最完整的分支。第 1 步在 App 配置中注册 scheme。在app.json或app.config.js的scheme键下添加一个字符串{ expo: { scheme: com.supabase } }第 2 步在 Supabase 控制台登记 redirect URL。在项目的 Auth settings 中添加com.supabase://**对应上面的com.supabasescheme**是通配符可匹配任意路径通配符规则见 Redirect URLs 文档。第 3 步实现 OAuth 与回跳处理。下面是文档中给出的完整示例组件Auth.tsx。其中createSessionFromUrl负责从回跳 URL 里取出access_token/refresh_token并调用supabase.auth.setSession建立会话performOAuth走 OAuth 流程sendMagicLink发送 Magic Link。valid.emailsupabase.io是文档中的示例邮箱替换成真实用户邮箱即可import { Button } from react-native; import { makeRedirectUri } from expo-auth-session; import * as QueryParams from expo-auth-session/build/QueryParams; import * as WebBrowser from expo-web-browser; import * as Linking from expo-linking; import { supabase } from app/utils/supabase; WebBrowser.maybeCompleteAuthSession(); // required for web only const redirectTo makeRedirectUri(); const createSessionFromUrl async (url: string) { const { params, errorCode } QueryParams.getQueryParams(url); if (errorCode) throw new Error(errorCode); const { access_token, refresh_token } params; if (!access_token) return; const { data, error } await supabase.auth.setSession({ access_token, refresh_token, }); if (error) throw error; return data.session; }; const performOAuth async () { const { data, error } await supabase.auth.signInWithOAuth({ provider: github, options: { redirectTo, skipBrowserRedirect: true, }, }); if (error) throw error; const res await WebBrowser.openAuthSessionAsync( data?.url ?? , redirectTo ); if (res.type success) { const { url } res; await createSessionFromUrl(url); } }; const sendMagicLink async () { const { error } await supabase.auth.signInWithOtp({ email: valid.emailsupabase.io, options: { emailRedirectTo: redirectTo, }, }); if (error) throw error; // Email sent. }; export default function Auth() { // Handle linking into app from email app. const url Linking.useLinkingURL(); if (url) createSessionFromUrl(url); return ( Button onPress{performOAuth} titleSign in with GitHub / Button onPress{sendMagicLink} titleSend Magic Link / / ); }关键点Linking.useLinkingURL()负责捕获“从邮件 App 点进 App”的深链场景Magic LinkWebBrowser.openAuthSessionAsync的返回值负责捕获 OAuth 回调场景两者最终都走createSessionFromUrl。替代平台一AndroidKotlin适用于 Supabase Android/Kotlin 客户端的项目。第 1 步同样先在 Auth settings 的Additional Redirect URLs填入[YOUR_SCHEME]://[YOUR_HOSTNAME]例如文档示例io.supabase.user-management://login-callback。第 2 步在 AndroidManifest 中为处理回跳的 activity 添加 intent-filter把YOUR_SCHEME/YOUR_HOSTNAME替换为第 1 步选定的值manifest ... !-- ... other tags -- application ... activity ... !-- ... other tags -- !-- Deep Links -- intent-filter action android:nameandroid.intent.action.VIEW / category android:nameandroid.intent.category.DEFAULT / category android:nameandroid.intent.category.BROWSABLE / !-- Accepts URIs that begin with YOUR_SCHEME://YOUR_HOST -- data android:schemeYOUR_SCHEME android:hostYOUR_HOSTNAME / /intent-filter /activity /application /manifest第 3 步在初始化 Supabase Client 时指定 host 与 schemeinstall(Auth) { host login-callback scheme io.supabase.user-management }第 4 步在 App 打开时调用Auth#handleDeeplinks处理意图override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supabase.handleDeeplinks(intent) }替代平台二Flutter文档说明supabase_flutter目前支持 Deep Links 的平台为 Android、iOS、Web、macOS 和 Windows。在控制台登记回调 URL 后示例io.supabase.flutterquickstart://login-callback按平台声明 schemeAndroid 端在 Manifest 中加入与上文相同的 intent-filterandroid:host属性对 Deep Links 是可选的iOS 端在ios/Runner/Info.plist或 Xcode Target Info 编辑器的 URL Types中声明 scheme!-- ... other tags -- plist dict !-- ... other tags -- keyCFBundleURLTypes/key array dict keyCFBundleTypeRole/key stringEditor/string keyCFBundleURLSchemes/key array string[YOUR_SCHEME]/string /array /dict /array !-- ... other tags -- /dict /plist其中[YOUR_SCHEME]需替换为你的 scheme例如io.supabase.flutterquickstart。替代平台三SwiftiOS第 1 步在 Auth settings 的Additional Redirect URLs填入回调 URL例如文档示例io.supabase.user-management://login-callback。第 2 步用 Xcode 的 Target Info EditorURL Types注册自定义 URL Scheme或手动在Info.plist中声明?xml version1.0 encodingUTF-8? !DOCTYPE plist PUBLIC -//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd plist version1.0 dict !-- other tags -- keyCFBundleURLTypes/key array dict keyCFBundleTypeRole/key stringEditor/string keyCFBundleURLSchemes/key array stringio.supabase.user-management/string /array /dict /array /dict /plist第 3 步操作系统通过回跳 URL 打开 App 后把 URL 传给supabase.auth.handle(_:)完成登录。SwiftUI 用根视图的onOpenURL修饰符SomeView() .onOpenURL { url in supabase.auth.handle(url) }UIKit 项目则要在两个时机转发 URLapplication(_:open:options:)App 运行中收到 URL以及didFinishLaunchingWithOptions中检查launchOptions?[.url]通过链接冷启动 App 的场景。使用 Scene Delegate 的项目对应scene(_:willConnectTo:options:)与scene(_:openURLContexts:)。文档说明handle(_:)是一个便捷封装内部调用session(from:)并记录错误日志如果需要拿返回的Session或自己控制错误处理可以直接调用session(from:)。可选分支iOS Universal Links以上方案使用自定义 URL Scheme。文档建议在追求更好体验时使用 Universal Links用户点链接可直接打开 App不出现浏览器跳转提示这属于可选的进阶配置要求在 Xcode 项目中配置 Associated Domains capability格式为applinks:yourdomain.com由你自己的基础设施托管 Apple App Site AssociationAASA文件需通过 HTTPS 无重定向提供、Content-Type为application/json或text/json、路径无文件扩展名.well-known/apple-app-site-association或根路径下的apple-app-site-association。AASA 文件格式示例来自 Universal Links 说明{ applinks: { apps: [], details: [ { appID: TEAM_ID.BUNDLE_ID, paths: [*] } ] } }把TEAM_ID替换为 Apple Developer Team IDBUNDLE_ID替换为 App 的 bundle identifier。注意 Supabase 目前不支持托管 AASA 文件必须自行托管。结果验证与错误处理配置是否成功按文档给出的行为判断Kotlin文档的结论是当 App 收到有效的 deep link 时用户即完成认证The user will now be authenticated when your app receives a valid deep link。React Native回跳 URL 经QueryParams.getQueryParams解析后应包含access_token与refresh_tokensetSession返回的data.session即成功建立的会话解析出errorCode时应抛出错误如上文createSessionFromUrl所示。认证失败的情况即使认证失败用户仍会被重定向到 redirect URL错误细节以查询参数形式附在 URL 上。可以解析这些参数并展示自定义错误信息Redirect URLs 文档给出的示例是读取error_code以4开头表示 4xx 错误与error_descriptionconst params new URLSearchParams(window.location.hash.slice()) if (params.get(error_code).startsWith(4)) { // show error message if error is a 4xx error window.alert(params.get(error_description)) }限制与注意事项Redirect URL 的注册是前置必要条件redirectTo/emailRedirectTo使用的地址必须与 Auth settings 中登记的列表匹配回跳才能被接受。生产环境文档建议使用精确的回调地址而非**通配**通配更适合本地开发与预览环境。supabase_flutter的 Deep Links 支持范围为 Android、iOS、Web、macOS 和 WindowsFlutter Windows/macOS 还需要额外步骤Windows 需手动修改win32_window.h/.cpp并自行注册 URL 协议macOS 需在macos/Runner/Info.plist中声明CFBundleURLTypes细节见 Deep Linking 文档对应 Tab。使用redirectTo选项时自定义邮件模板中可能需要把{{ .SiteURL }}替换为{{ .RedirectTo }}这一点见 Email Templates 文档。【免费下载链接】supabaseThe Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.项目地址: https://gitcode.com/GitHub_Trending/supa/supabase创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考