0Pricing
React Native Academy · Ders

E-posta ve OAuth Kimlik Doğrulaması

E-posta/parola ile kayıt ve oturum açmayı uygulayın, yönlendirme akışı için WebBrowser kullanarak Google OAuth ekleyin ve uygulama yeniden başlatmaları arasında oturumu koruyun.

E-posta ve OAuth Kimlik Doğrulaması, CoddyKit'te ücretsiz bir React Native Academy dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, React Native Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. React Native Academy kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Authentication Options in Supabase

Supabase Auth supports multiple authentication strategies out of the box: email/password, magic link (passwordless email), OAuth providers (Google, Apple, GitHub, etc.), and phone OTP. All of these are accessible through the same supabase.auth API.

For React Native, the most common flows are email/password for simplicity and Google/Apple OAuth for a polished native experience. Supabase manages token storage, refresh, and expiry automatically when AsyncStorage is configured.

Sign Up with Email and Password

To register a new user, call supabase.auth.signUp with the email and password. Supabase creates the user in the auth.users table and sends a confirmation email. The returned data.session will be null until the user confirms their email, unless you disable email confirmation in the Supabase dashboard.

Always check for the error field in the response and display a meaningful message to the user if sign-up fails.

import { supabase } from '../lib/supabase';

async function signUp(email: string, password: string) {
  const { data, error } = await supabase.auth.signUp({
    email,
    password,
  });

  if (error) {
    console.error('Sign up error:', error.message);
    return null;
  }

  // data.user is available; data.session may be null until email confirmed
  return data.user;
}

Sign In with Email and Password

For returning users, call supabase.auth.signInWithPassword. On success, Supabase returns a session with a JWT and a refresh token. With persistSession: true, the client saves this session to AsyncStorage automatically.

If the user enters the wrong credentials, the error will have a message like Invalid login credentials. Map this to a user-friendly message like Email or password is incorrect rather than exposing internal error text.

async function signIn(email: string, password: string) {
  const { data, error } = await supabase.auth.signInWithPassword({
    email,
    password,
  });

  if (error) {
    Alert.alert('Login Failed', 'Email or password is incorrect.');
    return;
  }

  // Session is saved automatically; navigate to main app
  console.log('Signed in as:', data.user?.email);
}

Sign Out

Signing out is straightforward: call supabase.auth.signOut(). This invalidates the session on the server, clears it from AsyncStorage, and triggers the SIGNED_OUT event in onAuthStateChange.

A good UX pattern is to navigate the user to the login screen inside the onAuthStateChange listener rather than directly after calling signOut, so that all parts of the app respond consistently to the auth state change regardless of where signOut is triggered from.

async function signOut() {
  const { error } = await supabase.auth.signOut();
  if (error) {
    console.error('Sign out error:', error.message);
  }
  // Navigation to login happens in onAuthStateChange listener
}

Building an Auth Screen Component

A typical auth screen holds email and password in component state, provides Sign In and Sign Up buttons, and displays a loading indicator while the async call is in progress. Keep the form simple: two TextInput components and two TouchableOpacity buttons are enough for a functional login screen.

Use the keyboardType='email-address' prop on the email field and secureTextEntry on the password field to improve the user experience on mobile keyboards.

import { useState } from 'react';
import { View, TextInput, TouchableOpacity, Text, ActivityIndicator } from 'react-native';
import { supabase } from '../lib/supabase';

export function AuthScreen() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleSignIn() {
    setLoading(true);
    await supabase.auth.signInWithPassword({ email, password });
    setLoading(false);
  }

  return (
    <View>
      <TextInput value={email} onChangeText={setEmail} keyboardType='email-address' />
      <TextInput value={password} onChangeText={setPassword} secureTextEntry />
      {loading ? <ActivityIndicator /> : (
        <TouchableOpacity onPress={handleSignIn}>
          <Text>Sign In</Text>
        </TouchableOpacity>
      )}
    </View>
  );
}

OAuth with Google: Installing Dependencies

OAuth in React Native requires opening an external browser for the provider's consent screen and then capturing the redirect back to the app. The recommended approach with Expo uses expo-web-browser and expo-auth-session.

Install these packages with npx expo install expo-web-browser expo-auth-session. You must also configure a redirect URL that the browser can use to return control to your app after the user grants consent. In Expo, this URL looks like exp://your.project/--/auth/callback in development.

npx expo install expo-web-browser expo-auth-session

# In app.json, register a deep-link scheme:
# {
#   'expo': {
#     'scheme': 'myapp'
#   }
# }
#
# This makes the redirect URL:
# myapp://auth/callback

Performing the Google OAuth Flow

Call supabase.auth.signInWithOAuth to get the OAuth URL, then open it with WebBrowser.openAuthSessionAsync. When the browser redirects back to your app with the session tokens in the URL, extract them and call supabase.auth.setSession.

You must register your redirect URL in the Supabase dashboard under Authentication > URL Configuration > Redirect URLs and also configure your app's custom scheme so the OS routes the redirect back correctly.

import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
import { supabase } from '../lib/supabase';

async function signInWithGoogle() {
  const redirectUrl = Linking.createURL('/auth/callback');

  const { data, error } = await supabase.auth.signInWithOAuth({
    provider: 'google',
    options: { redirectTo: redirectUrl },
  });

  if (error || !data.url) return;

  const result = await WebBrowser.openAuthSessionAsync(data.url, redirectUrl);

  if (result.type === 'success') {
    const { url } = result;
    // Extract tokens from URL and set session
    const parsedUrl = new URL(url);
    const accessToken = parsedUrl.searchParams.get('access_token')!;
    const refreshToken = parsedUrl.searchParams.get('refresh_token')!;
    await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken });
  }
}

Getting the Current User

After sign-in, you can retrieve the currently authenticated user at any time by calling supabase.auth.getUser(). This validates the JWT with the Supabase server, making it more secure than reading the cached session.user object.

For performance-sensitive cases where you just need the user's ID, reading session?.user from supabase.auth.getSession() avoids a network round-trip. Use getUser() for security-sensitive operations and getSession() for display purposes.

// Secure: validates with Supabase server
async function getAuthenticatedUser() {
  const { data: { user }, error } = await supabase.auth.getUser();
  if (error) {
    console.error('Auth error:', error.message);
    return null;
  }
  return user; // { id, email, created_at, ... }
}

// Fast: reads from local cache
async function getUserFromSession() {
  const { data: { session } } = await supabase.auth.getSession();
  return session?.user ?? null;
}

Protecting Screens Based on Auth State

A clean pattern for protecting screens is to create a root navigator that watches the Supabase session and switches between an auth stack and a main app stack based on whether a session exists.

Place the onAuthStateChange listener in the root layout component. When the session is null, render the login screens; when a session is present, render the main app screens. React Navigation handles the transition automatically.

import { NavigationContainer } from '@react-navigation/native';
import { useSession } from '../hooks/useSession';

export function RootNavigator() {
  const session = useSession(); // custom hook using onAuthStateChange

  return (
    <NavigationContainer>
      {session ? <AppStack /> : <AuthStack />}
    </NavigationContainer>
  );
}

Password Reset Flow

Supabase provides a built-in password reset flow. Call supabase.auth.resetPasswordForEmail with the user's email address. Supabase sends an email with a magic link. When the user taps the link, they land on a reset password page where they can set a new password.

In a mobile deep-link setup, you configure the redirect URL to point back to your app, where you then call supabase.auth.updateUser({ password: newPassword }) after the user enters their new credentials.

// Step 1: Send password reset email
async function requestPasswordReset(email: string) {
  const { error } = await supabase.auth.resetPasswordForEmail(email, {
    redirectTo: 'myapp://auth/reset-password',
  });
  if (!error) {
    Alert.alert('Check your email', 'A password reset link has been sent.');
  }
}

// Step 2: After the user follows the link and is redirected to the app,
// update their password:
async function updatePassword(newPassword: string) {
  const { error } = await supabase.auth.updateUser({ password: newPassword });
  if (!error) {
    Alert.alert('Success', 'Your password has been updated.');
  }
}

Handling Auth Errors Gracefully

Always handle authentication errors in a user-friendly way. Common Supabase auth errors include:

  • Invalid login credentials — wrong email or password
  • User already registered — email is taken during sign-up
  • Email not confirmed — user signed up but has not confirmed their email yet

Map these technical messages to clear UI messages. Consider storing a authError string in state and displaying it beneath the form fields in a red Text component.

const ERROR_MESSAGES: Record<string, string> = {
  'Invalid login credentials': 'Email or password is incorrect.',
  'User already registered': 'This email is already in use.',
  'Email not confirmed': 'Please confirm your email before signing in.',
};

async function handleSignIn(email: string, password: string) {
  const { error } = await supabase.auth.signInWithPassword({ email, password });
  if (error) {
    const friendlyMessage = ERROR_MESSAGES[error.message] ?? 'An error occurred. Try again.';
    setAuthError(friendlyMessage);
  }
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: how to implement email/password sign-up and sign-in, how to perform OAuth with Google using expo-web-browser, and how to protect navigation routes based on the Supabase auth session. Next up we explore querying the Supabase database from React Native components.

Sıkça Sorulan Sorular

“E-posta ve OAuth Kimlik Doğrulaması” dersi ücretsiz mi?

Evet — “E-posta ve OAuth Kimlik Doğrulaması” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve React Native Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. React Native Academy kursu toplamda 4 dersten oluşur.

“E-posta ve OAuth Kimlik Doğrulaması” dersinde ne öğreneceğim?

E-posta/parola ile kayıt ve oturum açmayı uygulayın, yönlendirme akışı için WebBrowser kullanarak Google OAuth ekleyin ve uygulama yeniden başlatmaları arasında oturumu koruyun. React Native Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

React Native Academy öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te React Native Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“E-posta ve OAuth Kimlik Doğrulaması” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu React Native Academy dersinde kod yazıp çalıştırabilir miyim?

Evet. Her React Native Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. React Native'de Supabase İstemcisini Kurma
  2. E-posta ve OAuth Kimlik Doğrulaması
  3. Supabase İstemcisiyle Veritabanını Sorgulama
  4. Gerçek Zamanlı Abonelikler
← React Native Academy Sayfasına Dön