flutterfirebasedartfirebase-authenticationmicrosoft-oauth

Implement Microsoft Auth w/ Firebase on Flutter Mobile App


I want to incorporate Microsoft Login into this Flutter app. My school is hosting a competition, and all participants have Microsoft accounts. Integrating these accounts into the mobile app would be beneficial. I've already implemented the web version, which authenticates with Firebase. Now, I aim to create a mobile version that also authenticates with Firebase through Microsoft accounts. How can I achieve this? Is it possible to use a popup screen on mobile, similar to the web version? Below is the code that facilitates this functionality on the web, and I want to adapt it for mobile. Currently, the function triggers a popup when a button is clicked, guiding users through Microsoft's login process. However, I also have email and password fields available, which could be utilized for the mobile implementation.

_loginWithMicrosoft() async {
        try {
          final provider = OAuthProvider("microsoft.com");
          provider.setCustomParameters({
            "tenant": "common",
            "prompt": "select_account",
          });
    
          // MicrosoftAuthCredential mAuth = Credential();
          debugPrint("Trying to pop-up microsoft login");
          UserCredential cred;
          if (kIsWeb) {
            debugPrint("On the web");
            FirebaseAuth.instance.signOut();
            cred = await FirebaseAuth.instance.signInWithPopup(provider);
            debugPrint(cred.user?.displayName);
            debugPrint(cred.user?.email);
          } else {
            debugPrint("Not on web");
            try {
              // TODO implement normal sign in without microsoft
              // given a username & password, send info and authenticate                               // firebase with microsoft login info. If possible w/ popup
              // cred = await FirebaseAuth.instance.whateverMethodGetsLoginAtMicroSoft
            } on FirebaseAuthException catch (e) {
              errorMessage = "${e.code} - ${e.message}";
              debugPrint(errorMessage);
            }
          }
        } on FirebaseAuthException catch (e) {
          errorMessage = "${e.code} - ${e.message}";
          debugPrint(errorMessage);
        }
      }

Solution

  • see federated-auth#microsoft

    import 'package:firebase_auth/firebase_auth.dart';
    
        Future<UserCredential> signInWithMicrosoft() async {
          final microsoftProvider = MicrosoftAuthProvider();
          if (kIsWeb) {
            await FirebaseAuth.instance.signInWithPopup(microsoftProvider);
          } else {
            await FirebaseAuth.instance.signInWithProvider(microsoftProvider);
          }
        }