Day 3: Implementing User Authentication with Firebase/Auth0


#UserAuthentication #FirebaseAuth #SecureMobileApp

Welcome to Day 3 of Advanced Mobile App Security! Today, you’ll integrate user authentication into your app using Firebase Authentication or Auth0. This ensures that users are securely identified and authorized to access your app’s features.


What You’ll Learn Today

  1. Set up Firebase Authentication for email/password login.
  2. Use Auth0 for social logins like Google or Facebook.
  3. Handle user sessions securely in your app.

Step 1: Firebase Authentication Setup

1. Install Firebase Authentication

npm install @react-native-firebase/auth
npx pod-install

2. Enable Email/Password Login

  • Go to the Firebase Console.
  • Under Authentication > Sign-In Method, enable Email/Password.

Step 2: Build Firebase Authentication

1. Create an AuthService for Firebase

Create a file FirebaseAuthService.js:

import auth from '@react-native-firebase/auth';

export const registerUser = async (email, password) => {
  try {
    const userCredential = await auth().createUserWithEmailAndPassword(email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Registration Error:', error);
    throw error;
  }
};

export const loginUser = async (email, password) => {
  try {
    const userCredential = await auth().signInWithEmailAndPassword(email, password);
    return userCredential.user;
  } catch (error) {
    console.error('Login Error:', error);
    throw error;
  }
};

export const logoutUser = async () => {
  try {
    await auth().signOut();
    console.log('User logged out');
  } catch (error) {
    console.error('Logout Error:', error);
    throw error;
  }
};

Step 3: Auth0 Setup

1. Install Auth0 React Native SDK

npm install react-native-auth0

2. Configure Auth0

Create a file Auth0Service.js:

import Auth0 from 'react-native-auth0';

const auth0 = new Auth0({
  domain: 'your-auth0-domain.auth0.com',
  clientId: 'your-client-id',
});

export const loginWithAuth0 = async () => {
  try {
    const credentials = await auth0.webAuth.authorize({ scope: 'openid profile email' });
    console.log('Access Token:', credentials.accessToken);
    return credentials;
  } catch (error) {
    console.error('Auth0 Login Error:', error);
    throw error;
  }
};

export const logoutWithAuth0 = async () => {
  try {
    await auth0.webAuth.clearSession();
    console.log('User logged out');
  } catch (error) {
    console.error('Auth0 Logout Error:', error);
  }
};

Step 4: Build the Authentication UI

1. Create AuthScreen

Create a file AuthScreen.js:

import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import { registerUser, loginUser } from './FirebaseAuthService';
import { loginWithAuth0 } from './Auth0Service';

const AuthScreen = ({ onLoginSuccess }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isRegistering, setIsRegistering] = useState(false);

  const handleFirebaseAuth = async () => {
    try {
      const user = isRegistering ? await registerUser(email, password) : await loginUser(email, password);
      onLoginSuccess(user);
    } catch (error) {
      alert(error.message);
    }
  };

  const handleAuth0Login = async () => {
    try {
      const credentials = await loginWithAuth0();
      onLoginSuccess(credentials);
    } catch (error) {
      alert(error.message);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{isRegistering ? 'Register' : 'Login'}</Text>
      <TextInput
        style={styles.input}
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        keyboardType="email-address"
        autoCapitalize="none"
      />
      <TextInput
        style={styles.input}
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />
      <Button title={isRegistering ? 'Register' : 'Login'} onPress={handleFirebaseAuth} />
      <Button title="Login with Auth0" onPress={handleAuth0Login} />
      <Button
        title={isRegistering ? 'Switch to Login' : 'Switch to Register'}
        onPress={() => setIsRegistering(!isRegistering)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    marginBottom: 15,
  },
});

export default AuthScreen;

Step 5: Integrate Authentication into App.js

Update App.js:

import React, { useState } from 'react';
import AuthScreen from './AuthScreen';

const App = () => {
  const [user, setUser] = useState(null);

  return user ? (
    <View>
      <Text>Welcome, {user.email || user.name}!</Text>
    </View>
  ) : (
    <AuthScreen onLoginSuccess={(loggedInUser) => setUser(loggedInUser)} />
  );
};

export default App;

Step 6: Test Authentication

  1. Run the app: npx react-native run-android npx react-native run-ios
  2. Test Firebase Login:
    • Register a user with email and password.
    • Verify successful login and session handling.
  3. Test Auth0 Login:
    • Log in using Auth0 for social authentication.
    • Verify the retrieved access token.
See also  Intel HAXM: Unleashing Android Emulator Performance on Your Machine

Enhance Authentication (Optional)

  1. Session Persistence:
    • Store and retrieve authentication tokens securely using SecureStore or react-native-keychain.
  2. Multi-Factor Authentication (MFA):
    • Enable MFA in Firebase or Auth0 for additional security.
  3. Error Handling:
    • Display user-friendly error messages for failed login attempts.

SEO Optimization for This Tutorial

Keywords: Firebase authentication React Native, Auth0 social login, secure mobile app authentication, Firebase vs Auth0, React Native login screen.

Meta Description: Learn how to implement user authentication in a React Native app using Firebase or Auth0. This tutorial covers email/password login, social login, and secure session handling.


Summary

Today, you implemented user authentication using Firebase and Auth0. Users can now securely log in to your app using email/password or social accounts.

What’s Next: Tomorrow, you’ll learn to add biometric authentication (Face ID, fingerprint) for an enhanced login experience.

Stay tuned for Day 4: Adding Biometric Authentication.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.