teranetsrl / oauth2_client

Simple Dart library for interacting with OAuth2 servers.
BSD 2-Clause "Simplified" License
91 stars 111 forks source link

Using authentication for Firebase login on Flutter web #185

Closed maxbeech closed 3 months ago

maxbeech commented 3 months ago

Hi there!

Thanks for the awesome package. I've used it to get access to the Google Play Developer API, but would also like to use the same token/access code to authenticate the user in Firebase. How can I do this please?

Here's the code that first uses this package to authenticate:

signInWithGoogle() async {
  GoogleOAuth2Client client = GoogleOAuth2Client(
    customUriScheme: 'MY_URI_SCHEME',
    redirectUri: 'MY_REDRECT_URI',
  );

  try {
    OAuth2Helper oauth2Helper = OAuth2Helper(client,
        grantType: OAuth2Helper.authorizationCode,
        clientId: 'MY_CLIENT_ID',
        clientSecret: 'MY_SECRET',
        scopes: ['https://www.googleapis.com/auth/androidpublisher', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']);
    oauth2Helper.fetchToken(); // trigger sign in window (will actually grab the token later via getToken when we're ready to use it)

    // The webview will now have popped up, if user autentiates correctly, the webview will receieve the token
    // The webview wll then try to send the token back here via a POST message

    /// Listen to message send with `postMessage`.
    html.window.onMessage.listen((event) async {
      if (event.data.toString().contains('code=')) {
        Uri returnedUrl = Uri.parse(event.data.toString());
        String? authCode = returnedUrl.queryParameters["code"];

        if (authCode != null) {
          oauth2Helper.getToken().then((value) {
            String? accessToken = value?.accessToken;
            if (accessToken != null) {
              signIntoFirebase(authCode, accessToken);
            }
          });
        }
      }
    });
  } catch (err) {
    print("Error in oauth2Helper");
  }
}

Here's my attempt at then signing in with Firebase:

signIntoFirebase(String authCode, String accessToken) async {
  FirebaseAuth auth = FirebaseAuth.instance;
  OAuthCredential authCredential = GoogleAuthProvider.credential(
    accessToken: accessToken,
    idToken: authCode,
  );
  User? userFire = (await auth.signInWithCredential(authCredential)).user;

  if (userFire != null) {
    print("Authenticated!");
  } else {
    print("Couldn't authenticate with Firebase!");
  }
}

However I get this error when trying to sign into Firebase: Unable to parse Google id_token: TOKEN_HERE

What am I doing wrong please? Am I passing the wrong tokens into the Firebase function or is this whole idea just not possible?

Many thanks!

maxbeech commented 3 months ago

Ignore me, I didn't clock that I could request authentication of the Reply to Reviews API via Firebase's auth.