认证

在React Native中使用Supabase身份验证

学习如何在React Native中使用Supabase身份验证


1

创建新的Supabase项目

Supabase仪表盘启动一个新项目

您的新数据库已包含用于存储用户的表。您可以通过在SQL编辑器中运行SQL语句来查看当前该表为空。

SQL_EDITOR
1
select * from auth.users;
2

创建React应用

使用create-expo-app命令创建一个React应用。

Terminal
1
npx create-expo-app -t expo-template-blank-typescript my-app
3

安装Supabase客户端库

安装supabase-js及所需依赖项。

Terminal
1
cd my-app && npx expo install @supabase/supabase-js @react-native-async-storage/async-storage @rneui/themed react-native-url-polyfill
4

设置登录组件

创建一个辅助文件lib/supabase.ts,使用您的项目URL和公共API(anon)密钥导出一个Supabase客户端。

lib/supabase.ts
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
import { AppState } from 'react-native'import 'react-native-url-polyfill/auto'import AsyncStorage from '@react-native-async-storage/async-storage'import { createClient, processLock } from '@supabase/supabase-js'const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URLconst supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_ANON_KEYexport const supabase = createClient(supabaseUrl, supabaseAnonKey, { auth: { storage: AsyncStorage, autoRefreshToken: true, persistSession: true, detectSessionInUrl: false, lock: processLock, },})// 告诉Supabase Auth在应用处于前台时自动持续刷新会话// 添加此功能后,当用户会话终止时,您将继续收到带有`TOKEN_REFRESHED`或// `SIGNED_OUT`事件的`onAuthStateChange`通知。此功能应仅注册一次。AppState.addEventListener('change', (state) => { if (state === 'active') { supabase.auth.startAutoRefresh() } else { supabase.auth.stopAutoRefresh() }})
5

创建登录组件

让我们设置一个React Native组件来管理登录和注册功能。

components/Auth.tsx
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
72
73
74
75
76
77
78
79
80
81
82
83
import React, { useState } from 'react'import { Alert, StyleSheet, View } from 'react-native'import { supabase } from '../lib/supabase'import { Button, Input } from '@rneui/themed'export default function Auth() { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [loading, setLoading] = useState(false) async function signInWithEmail() { setLoading(true) const { error } = await supabase.auth.signInWithPassword({ email: email, password: password, }) if (error) Alert.alert(error.message) setLoading(false) } async function signUpWithEmail() { setLoading(true) const { data: { session }, error, } = await supabase.auth.signUp({ email: email, password: password, }) if (error) Alert.alert(error.message) if (!session) Alert.alert('请检查您的收件箱以完成邮箱验证!') setLoading(false) } return ( <View style={styles.container}> <View style={[styles.verticallySpaced, styles.mt20]}> <Input label="邮箱" leftIcon={{ type: 'font-awesome', name: 'envelope' }} onChangeText={(text) => setEmail(text)} value={email} placeholder="email@address.com" autoCapitalize={'none'} /> </View> <View style={styles.verticallySpaced}> <Input label="密码" leftIcon={{ type: 'font-awesome', name: 'lock' }} onChangeText={(text) => setPassword(text)} value={password} secureTextEntry={true} placeholder="密码" autoCapitalize={'none'} /> </View> <View style={[styles.verticallySpaced, styles.mt20]}> <Button title="登录" disabled={loading} onPress={() => signInWithEmail()} /> </View> <View style={styles.verticallySpaced}> <Button title="注册" disabled={loading} onPress={() => signUpWithEmail()} /> </View> </View> )}const styles = StyleSheet.create({ container: { marginTop: 40, padding: 12, }, verticallySpaced: { paddingTop: 4, paddingBottom: 4, alignSelf: 'stretch', }, mt20: { marginTop: 20, },})
6

将Auth组件添加到应用

Auth组件添加到您的App.tsx文件中。如果用户已登录,则在屏幕上显示用户ID。

App.tsx
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
import 'react-native-url-polyfill/auto'import { useState, useEffect } from 'react'import { supabase } from './lib/supabase'import Auth from './components/Auth'import { View, Text } from 'react-native'import { Session } from '@supabase/supabase-js'export default function App() { const [session, setSession] = useState<Session | null>(null) useEffect(() => { supabase.auth.getSession().then(({ data: { session } }) => { setSession(session) }) supabase.auth.onAuthStateChange((_event, session) => { setSession(session) }) }, []) return ( <View> <Auth /> {session && session.user && <Text>{session.user.id}</Text>} </View> )}
7

启动应用

启动应用,并按照终端中的指示操作。

Terminal
1
npm start