认证

原生移动应用深度链接

为移动应用程序设置深度链接


许多身份验证方法都涉及重定向到您的应用程序。例如:

  • 注册确认邮件、Magic Link登录和密码重置邮件中包含重定向到您应用的链接
  • 在OAuth登录过程中,会自动重定向到您的应用

通过深度链接(Deep Linking),您可以配置此重定向以打开特定页面。这在某些场景下是必需的,例如当您需要显示密码重置表单,或需要手动交换令牌哈希时。

设置深度链接

要链接到您的开发构建或独立应用,您需要为应用指定自定义URL方案。您可以在应用配置(app.json, app.config.js)中通过scheme键添加字符串来注册方案:

1
2
3
4
5
{ "expo": { "scheme": "com.supabase" }}

在项目的auth设置中添加重定向URL,例如com.supabase://**

最后,实现OAuth和链接处理程序。有关在React Native中初始化supabase-js客户端的说明,请参阅supabase-js参考文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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(); // 仅网页需要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.email@supabase.io", options: { emailRedirectTo: redirectTo, }, }); if (error) throw error; // 邮件已发送};export default function Auth() { // 处理从邮件应用进入的链接 const url = Linking.useURL(); if (url) createSessionFromUrl(url); return ( <> <Button onPress={performOAuth} title="使用Github登录" /> <Button onPress={sendMagicLink} title="发送魔法链接" /> </> );}

为了最佳用户体验,建议使用需要更复杂设置的通用链接。您可以在Expo文档中找到详细设置说明。