Skip to content
Auth

原生移动深度链接

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:

{
"expo": {
"scheme": "com.supabase"
}
}

在你项目的认证设置中添加重定向网址,例如 com.supabase://**。

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

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.email@supabase.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} title="使用 GitHub 登录" />
<Button onPress={sendMagicLink} title="发送魔法链接" />
</>
);
}

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