原生移动深度链接
Set up Deep Linking for mobile applications.
许多认证方法都需要重定向到你的应用。例如:
🌐 Many Auth methods involve a redirect to your app. For example:
- 注册确认邮件、Magic Link 登录和密码重置邮件都包含一个会将你重定向到应用的链接。
- 在 OAuth 登录中,会自动重定向到你的应用。
通过深度链接,你可以配置这个重定向去打开一个特定的页面。例如,如果你需要显示一个重置密码的表单,或者手动交换一个令牌哈希,这是必要的。
🌐 With Deep Linking, you can configure this redirect to open a specific page. This is necessary if, for example, you need to display a form for password reset, or to manually exchange a token hash.
设置深度链接 #
🌐 Setting up deep linking
To link to your development build or standalone app, you need to specify a custom URL scheme for your app. You can register a scheme in your app config (app.json, app.config.js) by adding a string under the scheme key:
1{2 "expo": {3 "scheme": "com.supabase"4 }5}在你项目的认证设置中添加重定向网址,例如 com.supabase://**。
最后,实现 OAuth 和链接处理程序。有关在 React Native 中初始化 supabase-js 客户端的说明,请参阅 supabase-js 参考。
1import { Button } from "react-native";2import { makeRedirectUri } from "expo-auth-session";3import * as QueryParams from "expo-auth-session/build/QueryParams";4import * as WebBrowser from "expo-web-browser";5import * as Linking from "expo-linking";6import { supabase } from "app/utils/supabase";78WebBrowser.maybeCompleteAuthSession(); // required for web only9const redirectTo = makeRedirectUri();1011const createSessionFromUrl = async (url: string) => {12 const { params, errorCode } = QueryParams.getQueryParams(url);1314 if (errorCode) throw new Error(errorCode);15 const { access_token, refresh_token } = params;1617 if (!access_token) return;1819 const { data, error } = await supabase.auth.setSession({20 access_token,21 refresh_token,22 });23 if (error) throw error;24 return data.session;25};2627const performOAuth = async () => {28 const { data, error } = await supabase.auth.signInWithOAuth({29 provider: "github",30 options: {31 redirectTo,32 skipBrowserRedirect: true,33 },34 });35 if (error) throw error;3637 const res = await WebBrowser.openAuthSessionAsync(38 data?.url ?? "",39 redirectTo40 );4142 if (res.type === "success") {43 const { url } = res;44 await createSessionFromUrl(url);45 }46};4748const sendMagicLink = async () => {49 const { error } = await supabase.auth.signInWithOtp({50 email: "valid.email@supabase.io",51 options: {52 emailRedirectTo: redirectTo,53 },54 });5556 if (error) throw error;57 // Email sent.58};5960export default function Auth() {61 // Handle linking into app from email app.62 const url = Linking.useLinkingURL();63 if (url) createSessionFromUrl(url);6465 return (66 <>67 <Button onPress={performOAuth} title="使用 GitHub 登录" />68 <Button onPress={sendMagicLink} title="发送魔法链接" />69 </>70 );71}为了获得最佳的用户体验,建议使用需要更复杂设置的通用链接。你可以在 Expo 文档 中找到详细的设置说明。