Flutter: Google SignIn without Firebase - flutter

I am trying to implement Google SignIn in flutter without using Firebase.
I am using Google SignIn package, taking idToken from there and sending it to my backend API for authentication.
I am getting pop up for selecting user email but after selecting, I am getting following error:
error: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null)
Below is my code in BLoC for handling Google SignIn:
if (event is GoogleSignInButtonPressed) {
yield LoginInProgress();
try {
GoogleSignIn _googleSignIn = GoogleSignIn(scopes:['email']);
GoogleSignInAccount user = await _googleSignIn.signIn();
print(user);
GoogleSignInAuthentication googleSignInAuthentication = await user.authentication;
String idToken = googleSignInAuthentication.idToken;
final token = await userRepository.authenticateWithGoogleSignIn(idToken: idToken);
authenticationBloc.add(AuthenticationLoggedIn(token: token));
yield LoginInitial();
} catch (error) {
yield LoginFailure(error: error.toString());
}

Firebase isn't required to use Google Sign-in. You can use google_sign_in plugin to authenticate the user. The ApiException that you're getting likely comes from not configuring the app properly on the Google Could API dashboard. Ensure that you've filled all the required fields on the OAuth console.

Related

Google sign in with Firebase on Flutter logs in without selecting google account or authorizing it

I'm trying to implement a sign in with google on a flutter app using firebaseAuth, the user can log in just fine, but I've realized that the app doesn't ask for a google account nor does it ask for authorization if I delete the account in the firebase console.
This is my google Sign in method:
Future<UserCredential> signInWithGoogle() async {
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
final GoogleSignInAuthentication? googleAuth =
await googleUser?.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken,
);
return await FirebaseAuth.instance.signInWithCredential(credential);
}
I've tried changing the way the sign out happens but nothing changed, currently using FirebaseAuth.instance.signOut()
For signing out.

Google_sign_in Org_internal unable to login with different account

I'm working on an application for my organization. I was trying to implement oAuth with the google_sign_in package based on our google accounts.
The process for members to log in with accounts that belongs to the organization works fine. That's not the case with external emails.
I was expecting an error to be thrown in google prompt but I'm unable to log in with different at all. Seams that google tries to log me in instantly each time, leading to this screen each time:
I've tried using GoogleSignIn().signOut() or .deactivate() methods both of those did nothing to either remove the cache or retrigger the signing process.
Code responsible for log in:
class FirebaseAuthExternalIdentityProvider implements ExternalIdentityProvider {
final FirebaseAuth _firebaseAuth;
FirebaseAuthExternalIdentityProvider({required FirebaseAuth firebaseAuth})
: _firebaseAuth = firebaseAuth;
#override
Future<Result<GoogleSignInTokenWrapper>> signInWithGoogle() async {
final GoogleSignInAccount? googleAccount = await GoogleSignIn().signIn();
if (googleAccount == null) {
return Result.failure(Failure.signInProcessAborted());
}
final GoogleSignInAuthentication? googleAuthStatus =
await googleAccount.authentication;
final OAuthCredential _firebaseCredential = GoogleAuthProvider.credential(
accessToken: googleAuthStatus?.accessToken,
idToken: googleAuthStatus?.idToken,
);
try {
return Result.success(GoogleSignInTokenWrapper(
accessToken: await (await _firebaseAuth
.signInWithCredential(_firebaseCredential))
.user!
.getIdToken(),
));
} on FirebaseAuthException catch (cause) {
return Result.failure(Failure.firebaseSignInException(cause: cause));
} on Exception catch (cause) {
return Result.failure(Failure.unexpected(cause: cause));
}
}
}
Does someone know how to handle this problem? Changing the OAuth consent screen to External is the last thing I want to consider doing.
Thanks for any help in this matter!

Error getting thrown when trying to sign in with Google Auth to Firestore

I am trying to create a google sign in option for my app. I appear to be getting back a valid Token Id from google but my app is crashing in the ios Emulator and the following error is being shown in console.
flutter: [firebase_auth/invalid-credential] Unable to parse Google id_token: ya29.A0ARrdaM_uqbYHorJh1kJXTXac7MEm2TjD.......
When I cancel the login an error is successfully being thrown from my code. Can anyone help me out?
flutter: [firebase_auth/sign_in_canceled] The user canceled the sign-in flow.
#override
Future<User?> signInWithGoogle() async {
final googleSignIn = GoogleSignIn();
final googleUser = await googleSignIn.signIn();
if (googleUser != null) {
final googleAuth = await googleUser.authentication;
if (googleAuth.idToken != null) {
final UserCredential = await _firebaseAuth
.signInWithCredential(GoogleAuthProvider.credential(
idToken: googleAuth.accessToken,
));
return UserCredential.user;
} else {
throw FirebaseAuthException(
code: 'ERROR_MISSING_GOOGLE_ID_TOKEN',
message: 'Missing Google ID Token',
);
}
} else {
throw FirebaseAuthException(
code: 'sign_in_canceled',
message: 'The user canceled the sign-in flow.',
);
}
}
I figured it out. This line needed to be changed to pass the idToken...not the accessToken.
idToken: googleAuth.idToken,

Flutter Web Google Sign In

I try to implement a signIn with Google in Flutter Web. I use GoogleSignn 4.1.1 and Firebase Auth 0.15.4. I do not get any error message. It just does not pop up.
I registered the web app in Firebase (Added Dependencies) and even added the <meta> Tag with the google-signin-client_id
The Firebase Auth with Google works when I run it on Android
I also ran the Example App from GoogleSignIn in Web. It also does not pop up.
This is my Login Code (Works on Android)
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.currentUser();
if (user != null) {
log.d('alreadyLoggedIn');
} else {
final GoogleSignIn _googleSignIn = GoogleSignIn(clientId: Constants.GOOGLE_SIGN_IN_CLIENT_ID);
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await _auth.signInWithCredential(credential);
user = await _auth.currentUser();
assert(user.email != null);
assert(user.displayName != null);
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
}
return user;
}
I hope someone knows how this can be fixed.
Have you followed all of the instructions (including adding OAuth ID to index.html) from this page?
https://pub.dev/packages/google_sign_in_web
You get your CLIENT ID from https://console.developers.google.com/apis/credentials
You also have to run from terminal like this, for it to work on localhost in debug:
flutter run -d chrome --web-hostname localhost --web-port 5000
The default authorised port is 5000, you can add other URIs on the same page you got your CLIENT ID (e.g.8764367243864-987523.apps.googleusercontent.com), it's under "Authorised JavaScript origins"
https://console.developers.google.com/apis/credentials)

How to connect facebook, firebase and flutter?

I'm following the instructions for incorporating facebook with android projects found here https://developers.facebook.com/apps/318154048893918/fb-login/quickstart/ and there is a step to download the Facebook SDK, but after that, it doesn't tell me where to put the file. The import statement it tells me to add won't work (says target of uri doesn't exist).
I'm trying to add the facebook user to our firebase database when they log in. I'm using flutter in android studio.
There doesn't seem to be anything of use in the console log, except that print statement doesn't print anything. Any ideas?
Here's my code to log in the user.
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
Future<FirebaseUser> initiateFacebookLogin() async {
final FacebookLoginResult result =
await facebookLogin.logInWithReadPermissions(['email', 'public_profile']);
FirebaseUser user =
await _auth.signInWithFacebook(accessToken: result.accessToken.token);
//Token: ${accessToken.token}
ProviderDetails userInfo = new ProviderDetails(
user.providerId, user.uid, user.displayName, user.photoUrl, user.email);
List<ProviderDetails> providerData = new List<ProviderDetails>();
providerData.add(userInfo);
print(user.displayName);
addToDatabase(user.uid, user.displayName, user.displayName, user.email);
return user;
}
In flutter you need use flutter_facebook_login plugin take a look here to see how to get the plugin and setup your flutter app to make use of this plugin. You can also check this article that is step-by-step about how setup you project and contains code example too but the API used is out of date.
Here a snippet with updated API showing how to achieve login in firebase with facebook account.
/// This mehtod makes the real auth
Future<FirebaseUser> firebaseAuthWithFacebook({#required FacebookAccessToken token}) async {
AuthCredential credential= FacebookAuthProvider.getCredential(accessToken: token.token);
FirebaseUser firebaseUser = await _authInstance.signInWithCredential(credential);
return firebaseUser;
}
In your code you're using _auth.signInWithFacebook method that is deprecated and you should replaced by signInWithCredential updating you firebase_auth plugin version.
///This object comes from facebook_login_plugin package
final facebookLogin = new FacebookLogin();
final facebookLoginResult = await facebookLogin
.logInWithReadPermissions(['email', 'public_profile']);
switch (facebookLoginResult.status) {
case FacebookLoginStatus.error:
print("Error");
break;
case FacebookLoginStatus.cancelledByUser:
print("CancelledByUser");
break;
case FacebookLoginStatus.loggedIn:
print("LoggedIn");
/// calling the auth mehtod and getting the logged user
var firebaseUser = await firebaseAuthWithFacebook(
token: facebookLoginResult.accessToken);
}
}