Firebase auth

From evanca/flutter-ai-rules · View interactive version

Firebase auth is an AI agent skill from the GitHub repository evanca/flutter-ai-rules. Use when setting up auth, managing auth state, implementing email/password or social sign-in, handling auth errors, or managing users.

How to use this skill

Skill file

Firebase Authentication Skill

This skill defines how to correctly use Firebase Authentication in Flutter applications.

When to Use

Use this skill when:


1. Setup and Configuration

flutter pub add firebase_auth
import 'package:firebase_auth/firebase_auth.dart';

Local emulator for testing:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await FirebaseAuth.instance.useAuthEmulator('localhost', 9099);
  // ...
}

2. Authentication State Management

Use the appropriate stream based on what you need to observe:

| Stream | Fires when |

|---|---|

| authStateChanges() | User signs in or out |

| idTokenChanges() | ID token changes (including custom claims) |

| userChanges() | User data changes (e.g., profile updates) |

FirebaseAuth.instance
  .authStateChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

3. Email and Password Authentication

Create a new account:

try {
  final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
    email: emailAddress,
    password: password,
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'weak-password') {
    print('The password provided is too weak.');
  } else if (e.code == 'email-already-in-use') {
    print('The account already exists for that email.');
  }
} catch (e) {
  print(e);
}

Sign in:

try {
  final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: emailAddress,
    password: password,
  );
} on FirebaseAuthException catch (e) {
  final String error = switch (e.code) {
    'invalid-email' => 'The email address is not valid.',
    // Email enumeration protection (default since Sep 2023) reports
    // 'invalid-credential' instead of 'user-not-found' / 'wrong-password';
    // older native SDKs report 'invalid-login-credentials'. Handle all four so
    // the app works with the setting on or off.
    'invalid-credential' ||
    'invalid-login-credentials' ||
    'user-not-found' ||
    'wrong-password' =>
      'The email address or password is incorrect.',
    'user-disabled' => 'This account has been disabled.',
    'too-many-requests' ||
    'network-request-failed' =>
      'Something went wrong. Try again later.',
    // Always keep a default branch — codes differ by platform and SDK version
    // (for example Windows reports 'unknown-error' for a wrong password).
    _ => 'Sign-in failed (${e.code}).',
  };
  print(error);
}

Share authentication state between Apple apps:

On Apple platforms, share auth state between apps in the same developer account by storing it in a shared Keychain access group. Enable the Keychain Sharing capability for each app with the same access group, then configure Firebase Auth with the fully qualified access group:

await FirebaseAuth.instance.setSettings(
  userAccessGroup: 'TEAMID.com.example.group1',
);

Switching from the default Keychain to a shared access group signs out the existing user unless migrated. Pass migrateCurrentUser: true (requires a non-null userAccessGroup) to preserve the current session, including an anonymous one — safe to call at app startup before any other Auth call, since it reads the existing session straight from the Keychain before Auth restores it. Migration can overwrite a user already stored in the destination access group.


4. Social Authentication

Google Sign-In (native platforms):

Future<UserCredential> signInWithGoogle() async {
  final GoogleSignInAccount? googleUser = await GoogleSignIn.instance.authenticate();
  final GoogleSignInAuthentication googleAuth = googleUser.authentication;
  final credential = GoogleAuthProvider.credential(idToken: googleAuth.idToken);
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

Google Sign-In (web):

Future<UserCredential> signInWithGoogle() async {
  GoogleAuthProvider googleProvider = GoogleAuthProvider();
  googleProvider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  googleProvider.setCustomParameters({'login_hint': 'user@example.com'});
  return await FirebaseAuth.instance.signInWithPopup(googleProvider);
}

```dart

final appleProvider = AppleAuthProvider();

appleProvider.addScope('email');

appleProvider.addScope('name');

```

```dart

// Apple platforms (iOS/macOS/web)

final authCode = userCredential.additionalUserInfo?.authorizationCode;

if (authCode != null) {

await FirebaseAuth.instance.revokeTokenWithAuthorizationCode(authCode);

}

// Android

final accessToken = userCredential.credential?.accessToken;

if (accessToken != null) {

await FirebaseAuth.instance.revokeAccessToken(accessToken);

}

```


5. Phone Number Authentication

Before using phone authentication, ensure platform-specific prerequisites are met:

Phone number sign-in is only supported on real devices and the web. Testing on device emulators is not supported.

iOS: recaptcha-sdk-not-linked error

On iOS, verifyPhoneNumber can throw FirebaseAuthException with code recaptcha-sdk-not-linked when Identity Platform expects reCAPTCHA Enterprise but the native SDK is not linked. This cannot be resolved from Dart — fix it at the native iOS or GCP level:


6. Error Handling


7. User Management

// Update profile
await FirebaseAuth.instance.currentUser?.updateProfile(
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg",
);

// Update email (sends verification to new address first)
await user?.verifyBeforeUpdateEmail("newemail@example.com");

8. Security Best Practices


9. Multi-Factor Authentication

Security warning: Avoid SMS-based MFA. SMS is insecure and easy to compromise or spoof.

Platform limitation: Windows does not support MFA. MFA with multiple tenants is not supported on Flutter.


10. Email Link Authentication

Important: Firebase Dynamic Links is deprecated for email link authentication. Firebase Hosting is now used to send sign-in links.


References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.