Bird
Raised Fist0
React Nativemobile~10 mins

Authentication (email, Google, Apple) in React Native

Choose your learning style10 modes available
Introduction

Authentication lets users prove who they are to your app. It keeps their data safe and personal.

When users need to create an account with their email and password.
When users want to sign in quickly using their Google account.
When users with Apple devices want to sign in using their Apple ID.
When you want to protect user data and personalize their experience.
When you want to allow easy login without remembering passwords.
Syntax
React Native
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import { appleAuth } from '@invertase/react-native-apple-authentication';

// Email sign-in example
const signInWithEmail = async (email, password) => {
  // Use your backend or Firebase to authenticate
};

// Google sign-in example
const signInWithGoogle = async () => {
  await GoogleSignin.hasPlayServices();
  const userInfo = await GoogleSignin.signIn();
  return userInfo;
};

// Apple sign-in example
const signInWithApple = async () => {
  const appleAuthRequestResponse = await appleAuth.performRequest({
    requestedOperation: appleAuth.Operation.LOGIN,
    requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
  });
  return appleAuthRequestResponse;
};

Use libraries like @react-native-google-signin/google-signin and @invertase/react-native-apple-authentication for easy integration.

Email sign-in usually requires a backend or Firebase to verify credentials.

Examples
This example shows how to send email and password to your server for authentication.
React Native
const signInWithEmail = async (email, password) => {
  // Call backend API to check email and password
  const response = await fetch('https://example.com/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });
  const data = await response.json();
  return data;
};
This example configures Google Sign-In and signs in the user.
React Native
import { GoogleSignin } from '@react-native-google-signin/google-signin';

GoogleSignin.configure({
  webClientId: 'your-web-client-id.apps.googleusercontent.com',
});

const signInWithGoogle = async () => {
  await GoogleSignin.hasPlayServices();
  const userInfo = await GoogleSignin.signIn();
  return userInfo;
};
This example requests Apple ID sign-in with email and full name scopes.
React Native
import { appleAuth } from '@invertase/react-native-apple-authentication';

const signInWithApple = async () => {
  const response = await appleAuth.performRequest({
    requestedOperation: appleAuth.Operation.LOGIN,
    requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
  });
  return response;
};
Sample App

This React Native app shows three ways to sign in: email, Google, and Apple. It uses simple checks for email and password, and real libraries for Google and Apple sign-in. The app shows messages to tell if sign-in worked or failed.

React Native
import React, { useState } from 'react';
import { View, Button, Text, TextInput, StyleSheet } from 'react-native';
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import { appleAuth } from '@invertase/react-native-apple-authentication';

GoogleSignin.configure({
  webClientId: 'your-web-client-id.apps.googleusercontent.com',
});

export default function AuthExample() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState('');

  const signInWithEmail = () => {
    if(email === 'user@example.com' && password === '123456') {
      setMessage('Email sign-in successful!');
    } else {
      setMessage('Email sign-in failed.');
    }
  };

  const signInWithGoogle = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const userInfo = await GoogleSignin.signIn();
      setMessage(`Google sign-in successful! Welcome ${userInfo.user.name}`);
    } catch (error) {
      setMessage('Google sign-in failed.');
    }
  };

  const signInWithApple = async () => {
    try {
      const response = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
      });
      setMessage('Apple sign-in successful!');
    } catch (error) {
      setMessage('Apple sign-in failed.');
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        keyboardType="email-address"
        autoCapitalize="none"
        accessibilityLabel="Email input"
      />
      <TextInput
        style={styles.input}
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
        accessibilityLabel="Password input"
      />
      <Button title="Sign in with Email" onPress={signInWithEmail} accessibilityLabel="Sign in with Email button" />
      <View style={{ height: 10 }} />
      <Button title="Sign in with Google" onPress={signInWithGoogle} accessibilityLabel="Sign in with Google button" />
      <View style={{ height: 10 }} />
      <Button title="Sign in with Apple" onPress={signInWithApple} accessibilityLabel="Sign in with Apple button" />
      <Text style={styles.message} accessibilityLiveRegion="polite">{message}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', padding: 20, backgroundColor: '#fff' },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 10, borderRadius: 5 },
  message: { marginTop: 20, fontSize: 16, color: 'green' },
});
OutputSuccess
Important Notes

Always test authentication on real devices because Google and Apple sign-in need device features.

Make sure to set up your app in Google and Apple developer consoles to get correct keys.

Use accessibility labels on inputs and buttons so screen readers can help users.

Summary

Authentication lets users securely access your app.

You can use email/password or social sign-ins like Google and Apple.

Use libraries to simplify integration and always handle success and failure states.

Practice

(1/5)
1. Which method is commonly used to authenticate users with their email and password in React Native apps?
easy
A. Using Firebase Authentication's signInWithEmailAndPassword method
B. Directly storing passwords in AsyncStorage
C. Using Google Sign-In without email
D. Using Apple Sign-In only

Solution

  1. Step 1: Understand email/password authentication

    Email/password authentication requires a secure backend or service like Firebase to verify credentials.
  2. Step 2: Identify the correct method in React Native

    Firebase provides signInWithEmailAndPassword to handle this securely and easily.
  3. Final Answer:

    Using Firebase Authentication's signInWithEmailAndPassword method -> Option A
  4. Quick Check:

    Email/password auth = Firebase signInWithEmailAndPassword [OK]
Hint: Email login usually uses Firebase's signInWithEmailAndPassword [OK]
Common Mistakes:
  • Storing passwords locally in AsyncStorage
  • Confusing social sign-in with email/password
  • Using Apple Sign-In for email login only
2. Which of the following is the correct syntax to import Google Sign-In in a React Native app?
easy
A. import { GoogleSignin } from '@react-native-google-signin/google-signin';
B. import GoogleSignIn from 'react-native-google-signin';
C. import Google from 'google-signin-react-native';
D. import { GoogleSignIn } from 'react-native-google-auth';

Solution

  1. Step 1: Recall the official Google Sign-In package

    The official package for React Native Google Sign-In is '@react-native-google-signin/google-signin'.
  2. Step 2: Check the correct import syntax

    The correct import uses named import { GoogleSignin } from that package.
  3. Final Answer:

    import { GoogleSignin } from '@react-native-google-signin/google-signin'; -> Option A
  4. Quick Check:

    Google Sign-In import = import { GoogleSignin } from '@react-native-google-signin/google-signin'; [OK]
Hint: Official Google Sign-In uses named import from '@react-native-google-signin/google-signin' [OK]
Common Mistakes:
  • Using default import instead of named import
  • Wrong package names
  • Confusing Google Sign-In with Apple Sign-In imports
3. What will be the output of this React Native code snippet when a user successfully signs in with Google?
async function onGoogleSignIn() {
  try {
    await GoogleSignin.hasPlayServices();
    const userInfo = await GoogleSignin.signIn();
    console.log(userInfo.user.email);
  } catch (error) {
    console.log('Error:', error.message);
  }
}
medium
A. Throws a syntax error due to missing await
B. Does nothing because signIn is not awaited
C. Logs 'Error: user cancelled the login flow' always
D. Logs the signed-in user's email to the console

Solution

  1. Step 1: Analyze the async function flow

    The function awaits Google Play services check and then awaits signIn, which returns user info.
  2. Step 2: Understand console.log output

    On success, userInfo.user.email is logged, so the user's email appears in the console.
  3. Final Answer:

    Logs the signed-in user's email to the console -> Option D
  4. Quick Check:

    Successful Google sign-in logs email [OK]
Hint: Await signIn returns user info; console logs email [OK]
Common Mistakes:
  • Forgetting to await signIn causing unresolved promise
  • Assuming error always occurs
  • Confusing userInfo structure
4. You wrote this code to sign in with Apple but get an error: "Apple Authentication is not configured properly." What is the likely cause?
import { appleAuth } from '@invertase/react-native-apple-authentication';

async function onAppleSignIn() {
  try {
    const appleAuthRequestResponse = await appleAuth.performRequest({
      requestedOperation: appleAuth.Operation.LOGIN,
      requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
    });
    console.log(appleAuthRequestResponse);
  } catch (error) {
    console.error(error);
  }
}
medium
A. Missing await keyword before performRequest
B. Apple Sign-In is not enabled in the Apple Developer portal for the app
C. requestedScopes array is empty
D. The import statement is incorrect

Solution

  1. Step 1: Understand Apple Sign-In setup requirements

    Apple Sign-In requires enabling the capability in Apple Developer portal for your app's bundle ID.
  2. Step 2: Identify the cause of configuration error

    The error indicates the app is not configured properly, usually meaning the capability is missing or misconfigured.
  3. Final Answer:

    Apple Sign-In is not enabled in the Apple Developer portal for the app -> Option B
  4. Quick Check:

    Configuration error = missing Apple Sign-In capability [OK]
Hint: Check Apple Developer portal for Sign-In capability [OK]
Common Mistakes:
  • Assuming code import is wrong
  • Ignoring Apple Developer portal setup
  • Forgetting to add requested scopes
5. You want to implement a unified sign-in button that lets users choose between Email, Google, or Apple sign-in in React Native. Which approach best handles this scenario?
hard
A. Use a single button that calls all sign-in methods simultaneously
B. Use only Google Sign-In and ignore others for simplicity
C. Create separate buttons for each method and handle their success/failure states individually
D. Store user passwords locally to switch between methods

Solution

  1. Step 1: Understand user experience for multiple sign-in options

    Users expect clear choices; separate buttons let them pick Email, Google, or Apple sign-in explicitly.
  2. Step 2: Manage success and failure states separately

    Each method has different flows and error handling, so handling them individually is best practice.
  3. Final Answer:

    Create separate buttons for each method and handle their success/failure states individually -> Option C
  4. Quick Check:

    Separate buttons + individual handling = best practice [OK]
Hint: Separate buttons for each sign-in method handle flows cleanly [OK]
Common Mistakes:
  • Trying to call all sign-ins at once
  • Ignoring Apple or Email sign-in options
  • Storing passwords insecurely on device
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard