User Authentication

Secure user login and registration in Flutter

🔐 What is User Authentication?

User authentication verifies user identity through login credentials. Flutter apps use Firebase Auth or custom backends to securely manage user accounts, passwords, and sessions for protected access to app features.


// Firebase Authentication example
await FirebaseAuth.instance.signInWithEmailAndPassword(
  email: email,
  password: password,
);
                                    

Key Authentication Concepts

📧

Email/Password

Traditional authentication using email address and password for user login and registration

FirebaseAuth.instance
  .signInWithEmailAndPassword(
    email: email, password: password
  );
🔑

OAuth

Social login with Google, Facebook, or Apple for quick and convenient authentication

GoogleSignIn().signIn();
📱

Phone Auth

Verify users with SMS codes sent to their phone number for secure authentication

FirebaseAuth.instance
  .verifyPhoneNumber(
    phoneNumber: phone
  );
👤

User State

Track logged-in user status and manage authentication state throughout the app

FirebaseAuth.instance
  .authStateChanges()
  .listen((user) {});

🔹 Firebase Setup

Add Firebase Authentication to your Flutter project:

# pubspec.yaml
dependencies:
  firebase_core: ^2.24.0
  firebase_auth: ^4.16.0
// Initialize Firebase in main.dart
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Result:

Firebase is initialized and ready to handle authentication in your app.

🔹 Email/Password Registration

Create new user accounts with email and password:

Future registerUser(String email, String password) async {
  try {
    UserCredential userCredential = 
      await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
    
    print('User registered: ${userCredential.user?.email}');
  } on FirebaseAuthException catch (e) {
    if (e.code == 'weak-password') {
      print('Password is too weak');
    } else if (e.code == 'email-already-in-use') {
      print('Email already exists');
    }
  }
}

Result:

New user account created and stored in Firebase Authentication.

🔹 Email/Password Login

Sign in existing users with their credentials:

Future loginUser(String email, String password) async {
  try {
    UserCredential userCredential = 
      await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
    
    print('User logged in: ${userCredential.user?.email}');
  } on FirebaseAuthException catch (e) {
    if (e.code == 'user-not-found') {
      print('No user found with this email');
    } else if (e.code == 'wrong-password') {
      print('Incorrect password');
    }
  }
}

Result:

User successfully authenticated and logged into the app.

🔹 Google Sign-In

Implement Google authentication for easy login:

# Add dependency
dependencies:
  google_sign_in: ^6.1.5
Future signInWithGoogle() async {
  // Trigger Google Sign-In flow
  final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

  // Obtain auth details
  final GoogleSignInAuthentication googleAuth = 
    await googleUser!.authentication;

  // Create credential
  final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  // Sign in to Firebase
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

Result:

User signs in using their Google account without creating a new password.

🔹 Check Authentication State

Monitor user login status in real-time:

class AuthWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        // User is logged in
        if (snapshot.hasData) {
          return HomeScreen();
        }
        // User is not logged in
        return LoginScreen();
      },
    );
  }
}

Result:

App automatically shows home screen for logged-in users, login screen for others.

🔹 Sign Out

Log out the current user:

Future signOut() async {
  await FirebaseAuth.instance.signOut();
  print('User signed out');
}

// In a button
ElevatedButton(
  onPressed: () async {
    await signOut();
    Navigator.pushReplacementNamed(context, '/login');
  },
  child: Text('Sign Out'),
)

Result:

User is logged out and redirected to the login screen.

🧠 Test Your Knowledge

Which Firebase method is used to create a new user account?