image

13 Mar 2026

9K

35K

Flutter & Firebase Auth: Implementing Single Sign-On (SSO) with OAuth Providers

In modern application development, providing a seamless and secure user authentication experience is paramount. Single Sign-On (SSO) addresses this need by allowing users to access multiple applications or services with a single set of credentials. When combined with the rapid development capabilities of Flutter and the robust backend services of Firebase Authentication, implementing SSO becomes remarkably efficient. This article delves into the professional implementation of SSO in Flutter applications using Firebase Authentication and popular OAuth providers.

Understanding Single Sign-On (SSO) and OAuth

Single Sign-On (SSO) is an authentication scheme that allows a user to log in with a single ID and password to gain access to a connected system of applications without being prompted for credentials again. It significantly enhances user experience by eliminating the need to remember multiple login credentials and streamlines access across various services.

OAuth (Open Authorization), on the other hand, is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites without giving them the passwords. OAuth providers like Google, Apple, Facebook, and GitHub simplify user registration and login by leveraging existing, trusted accounts.

Why Combine Flutter, Firebase Auth, and OAuth for SSO?

  • Enhanced User Experience: Users prefer signing in with familiar accounts, reducing friction and improving sign-up/login rates.
  • Simplified Development: Firebase Authentication abstracts away much of the complexity of managing user accounts, security, and integration with OAuth providers. Flutter's expressive UI toolkit allows for quick creation of intuitive authentication flows.
  • Robust Security: Firebase Auth handles security best practices, password hashing, and token management, significantly reducing the security burden on developers. OAuth providers offer robust, industry-standard authentication mechanisms.
  • Cross-Platform Consistency: Flutter ensures a consistent UI and authentication experience across iOS, Android, web, and desktop from a single codebase.
  • Scalability: Firebase scales automatically, handling authentication for millions of users without requiring backend infrastructure management.

Prerequisites

Before diving into the implementation, ensure you have the following:

  • Flutter SDK installed and configured.
  • A Firebase project set up in the Firebase Console.
  • Basic understanding of Flutter and Dart.

Step-by-Step Implementation

Step 1: Firebase Project Setup

First, you need to configure your Firebase project and enable the desired OAuth authentication methods.

1.1 Create/Open Firebase Project

Go to the Firebase Console, create a new project or open an existing one.

1.2 Add Flutter App to Firebase

Follow the instructions to add your Flutter application to Firebase for iOS, Android, and Web (if applicable). This involves downloading configuration files (`GoogleService-Info.plist` for iOS, `google-services.json` for Android) and adding Firebase initialization code.

1.3 Enable Authentication Providers

In the Firebase Console, navigate to "Authentication" in the left sidebar, then click on the "Sign-in method" tab. Here, enable the OAuth providers you wish to support (e.g., Google, Apple, Facebook).

  • Google: Simply enable it. Firebase automatically handles most of the configuration.
  • Apple: Requires an Apple Developer Account and configuration of a Services ID and Key.
  • Facebook: Requires a Facebook Developer account and creation of an app, providing an App ID and App Secret to Firebase.

Step 2: Flutter Project Setup

Next, set up your Flutter project by adding the necessary dependencies.

2.1 Create a New Flutter Project (if not already done)


flutter create my_sso_app
cd my_sso_app

2.2 Add Dependencies

Open your `pubspec.yaml` file and add the following dependencies. Always check pub.dev for the latest stable versions.


dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.24.2 # Use the latest version
  firebase_auth: ^4.15.2 # Use the latest version
  google_sign_in: ^6.1.6 # Use the latest version (for Google Sign-In)
  # For other providers, add their respective packages, e.g.,
  # flutter_facebook_auth: ^6.0.4
  # sign_in_with_apple: ^4.3.0

Run `flutter pub get` to fetch the packages.

2.3 Initialize Firebase in Flutter

In your `main.dart` file, initialize Firebase before running your app.


import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart'; // This file is generated by FlutterFire CLI

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter SSO Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const AuthWrapper(), // We'll create this widget later
    );
  }
}

The `firebase_options.dart` file is generated by the FlutterFire CLI. If you haven't generated it, run:


    flutter pub add firebase_core
    flutterfire configure
    

Step 3: Implementing Google Sign-In (Example)

Let's walk through implementing Google Sign-In as a primary example for an OAuth provider. The general pattern applies to other providers as well.

3.1 UI for Sign-In

Create a simple UI with a button to initiate the Google Sign-In process.


import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

class AuthScreen extends StatefulWidget {
  const AuthScreen({super.key});

  @override
  State createState() => _AuthScreenState();
}

class _AuthScreenState extends State {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  Future _signInWithGoogle() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) {
        // User canceled the sign-in
        return;
      }

      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      final OAuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // Sign in to Firebase with the Google credential
      final UserCredential userCredential = await _auth.signInWithCredential(credential);
      print("Signed in with Google: ${userCredential.user?.displayName}");
      // Navigate to home screen or update UI
    } catch (e) {
      print("Error signing in with Google: $e");
      // Show error to user
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to sign in with Google: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SSO Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Welcome! Please sign in.'),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              onPressed: _signInWithGoogle,
              icon: Image.asset(
                'assets/google_logo.png', // Add a Google logo to your assets folder
                height: 24.0,
              ),
              label: const Text('Sign in with Google'),
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.black, backgroundColor: Colors.white,
                minimumSize: const Size(220, 50),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                  side: const BorderSide(color: Colors.grey),
                ),
              ),
            ),
            // Add buttons for other providers similarly
          ],
        ),
      ),
    );
  }
}

Step 4: Managing Authentication State

To implement SSO effectively, your app needs to know if a user is currently logged in and react accordingly. Firebase Auth provides a powerful stream for this.

4.1 AuthWrapper Widget

Create an `AuthWrapper` widget that listens to Firebase authentication state changes and directs the user to the appropriate screen (login or home).


import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
// import 'package:my_sso_app/screens/auth_screen.dart'; // Your AuthScreen file
// import 'package:my_sso_app/screens/home_screen.dart'; // Your HomeScreen file

class AuthWrapper extends StatelessWidget {
  const AuthWrapper({super.key});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        } else if (snapshot.hasData) {
          // User is signed in
          return const HomeScreen();
        } else {
          // User is signed out
          return const AuthScreen();
        }
      },
    );
  }
}

// Dummy HomeScreen for demonstration
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  Future _signOut() async {
    await FirebaseAuth.instance.signOut();
  }

  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Welcome Home!'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: _signOut,
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Hello, ${user?.displayName ?? "Guest"}!'),
            Text('Email: ${user?.email ?? "N/A"}'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _signOut,
              child: const Text('Sign Out'),
            ),
          ],
        ),
      ),
    );
  }
}

Step 5: Sign Out Functionality

Implementing sign-out is straightforward with Firebase Authentication.


// In your HomeScreen or any relevant widget
Future _signOut() async {
  await FirebaseAuth.instance.signOut();
  await GoogleSignIn().signOut(); // Important for Google if you want to explicitly disconnect
  // For other providers, call their respective sign-out methods if available/needed
}

Calling `FirebaseAuth.instance.signOut()` logs the user out of Firebase. For OAuth providers like Google, it's often good practice to also call the provider's specific sign-out method (`GoogleSignIn().signOut()`) to clear their session on that provider's end, especially if you want to allow switching accounts.

Advanced Considerations

  • Error Handling: Implement robust error handling for network issues, invalid credentials, or provider-specific errors.
  • Linking Accounts: Firebase Auth allows linking multiple authentication providers to a single user account. This can be useful if a user initially signs up with Google but later wants to add Facebook as an alternative login method for the same account.
  • Custom Claims & Roles: Extend Firebase user profiles with custom claims to manage user roles and permissions within your application.
  • Anonymous Authentication: For certain apps, allow users to start anonymously and then upgrade their account by linking an OAuth provider.
  • Security Rules: Protect your Firebase data using Firebase Security Rules, referencing `request.auth.uid` to ensure only authenticated users (or specific roles) can access certain data.

Conclusion

Implementing Single Sign-On with Flutter and Firebase Authentication using OAuth providers offers a powerful, secure, and user-friendly authentication solution. By leveraging Firebase's managed service and Flutter's cross-platform capabilities, developers can rapidly build applications with seamless login experiences, focusing more on core features and less on the complexities of authentication backend. This approach not only streamlines the development process but also significantly enhances user satisfaction by providing convenient and trusted login options.

Related Articles

May 14, 2026

Building a Multi-Event Countdown Timer Widget with Reminders, Notifications, Repeat, and Custom Labels in Flutter

Building a Multi-Event Countdown Timer Widget with Reminders, Notifications, Repeat, and Custom Labels in Flutter Countdown timers are essential in many applic

May 11, 2026

Unleashing Dynamic UIs: Flutter's Animation Prowess

Unleashing Dynamic UIs: Flutter's Animation Prowess for Slide & Scale Effects Flutter's declarative UI framework, combined with its powerful animation capabilit

May 11, 2026

Building a Product Detail Page Widget in Flutter with Related Items, Review Carousel, Promo Badges, and Quick Buy

Building a Product Detail Page Widget in Flutter with Related Items, Review Carousel, Promo Badges, and Quick Buy A well-designed Product Detail Page (PDP) is