Flutter Firebase Auth / Google_sign_in fail to login with statuscode=CANCELED - firebase

This is my pubspec.yaml. I'm using Flutter:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
shared_preferences: ^0.4.2
json_serializable: ^1.2.1
camera: ^0.2.3
path_provider: ^0.4.1
simple_permissions: ^0.1.6
share: ^0.5.3
#Google Sign_In
firebase_auth: ^0.5.20
google_sign_in: ^3.0.5
I cannot authenticate with the Google Sign In method. The window shows up normally and after my app throws a error:
PlatformException(sign_in_failed, Status{statusCode=CANCELED, resolution=null}, null)
Haven't found any solutions online, can someone help me out?
The following is my _signIn() method
Future<FirebaseUser> _signIn() async {
GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
GoogleSignInAuthentication gSA = await googleSignInAccount.authentication;
FirebaseUser user = await auth.signInWithGoogle(
idToken: gSA.idToken, accessToken: gSA.accessToken);
print("User Name : ${user.displayName}");
return user;
}
My code crashes after I call GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn(); so my guess was, that my setup was wrong.
This is how I call the _signIn()
MaterialButton(
child: Text("Google Sign-In"),
onPressed: (){
_signIn()
.then((FirebaseUser user) => print(user))
.catchError((e) => print(e));
},
),
I already deleted the Firebase-Project on the google dev console online and created a new one. Also I tried the anonymous login -> worked fine
Any help is appreciated

I just ran into the same issue.
This is how I solved it.
1) Get your SHA1 certificate key. (see https://developers.google.com/android/guides/client-auth)
2) Place the SHA1 key in your Firebase console
3) Rebuild your flutter App and try again. It should be working now.

Okay, so I managed to fix this problem with using a APK in release mode!
What you have to do:
Build your app in release mode and add the SHA1 or SHA256 to your firebase project.
If you don't know how to prepare your app for release you can do this quickly.

Related

Flutter Google Sign-in, stuck after selecting account

I am running into issue trying to signin to Firebase with Google Sign-in in my Flutter app.
I've seen two other posts about this, but no answers that resolve it for myself. I am using Google Sign-in provider in flutter, google_sign_in: ^5.1.0, Flutter ver 2.2.1
I have followed the instructions on generating/adding the Sha-1, Sha-256 keys to my firebase project. Prior to that , I was getting an API exception. I added the keys, downloaded the latest google-json file to my android folder and got beyond that error. Now, when I click to Sign-in, I get the account selection screen.
I select my account, and then I hit a white page with endless spinner.
Here is the login code I'm running.
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
Future<void> _handleGoogleSignIn() async {
try {
GoogleSignInAccount? googleSignInAccount =
await _googleSignIn.signIn();
GoogleSignInAuthentication? googleSignInAuthentication =
await googleSignInAccount?.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication?.accessToken,
idToken: googleSignInAuthentication?.idToken,
);
final UserCredential user = await _auth.signInWithCredential(credential);
} catch (error) {
print('in error block');
print(error);
}
}
In doing some debug, it doesn't seem to get beyond the initial line:
GoogleSignInAccount? googleSignInAccount =
await _googleSignIn.signIn();
But I don't get any error, any warning, nothing...just a spinner that sits indefintely.
Any ideas on how to solve this, or at minimum , debug this without getting an error?
Thx
After digging further, I found he answer on the same bug reported on the Flutter github account.
https://github.com/flutter/flutter/issues/89169
The solution:
In the following code snippet (which is defined as default setup)
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
Change https://www.googleapis.com/auth/contacts.readonly (restricted scope) to https://www.googleapis.com/auth/userinfo.profile (non-restricted scope).
After that, OAuth screen will proceed with sign in.

Flutter Error Message: "message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":"AytUa8J8UWtBAqzv4-76M4c"

I would like to ask for help regarding this error. I am currently connecting facebook authentication in firebase to flutter. It's supposed to get data but it shows this error. Please check this out. thanks!
Here is my code.
final FirebaseAuth _auth = FirebaseAuth.instance;
var token;
void _signInFacebook() async {
var fbLogin = FacebookLogin();
var result = await fbLogin.logIn(['email']);
final graphResponse = await http.get('https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=${token}');
print(graphResponse.body);
if (result.status == FacebookLoginStatus.loggedIn) {
FacebookAccessToken myToken = result.accessToken;
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken: myToken.token);
var user = await FirebaseAuth.instance.signInWithCredential(credential);
}
}
Here is the error output.
I/flutter (17535): {"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":"A64iqiLEAMXv67OEALVxSDE"}}
My dependencies:
flutter_facebook_login: ^3.0.0
http: ^0.12.0+4
firebase_core: ^0.4.4+3
firebase_auth: ^0.14.0+5
Heres my build.gradle inside android
minSdkVersion 23
targetSdkVersion 29
You need to add your hashkey's in developer.facebook.com console.

Can we use 'Firestore' like this?

I downloaded flutter chat app on Github and I was learning through it. The original developer used Firestore but in mine, I am getting an error "Undefined name 'Firestore'.
Try correcting the name to one that is defined, or defining the name" like this.
I search for this and I read in cloudfirestore docs we can use "FirebaseFirestore" (maybe I am wrong). I am learning to write backend with flutter and so far I did UI parts. so this is my first attempt at learning backend with flutter.
handleSignIn() async {
final res = await googleSignIn.signIn();
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final auth = await res.authentication;
final credentials = GoogleAuthProvider.getCredential(
idToken: auth.idToken, accessToken: auth.accessToken);
final firebaseUser =
(await firebaseAuth.signInWithCredential(credentials)).user;
if (firebaseUser != null) {
final result = (await Firestore.instance
.collection('users')
.where('id', isEqualTo: firebaseUser.uid)
.getDocuments())
.documents;
if (result.length == 0) {
///new user
Firestore.instance
.collection('users')
.document(firebaseUser.uid)
.setData({
"id": firebaseUser.uid,
"name": firebaseUser.displayName,
"profile_pic": firebaseUser.photoURL,
"created_at": DateTime.now().millisecondsSinceEpoch,
});
sharedPreferences.setString("id", firebaseUser.uid);
sharedPreferences.setString("name", firebaseUser.displayName);
sharedPreferences.setString("profile_pic", firebaseUser.photoURL);
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Home()));
} else {
///Old user
sharedPreferences.setString("id", result[0]["id"]);
sharedPreferences.setString("name", result[0]["name"]);
sharedPreferences.setString("profile_pic", result[0]["profile_pic"]);
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Home()));
}
}
}
this is the error I'm getting
so can you guys explain how to solve this error?
Thank You.
I think you are missing to add cloud_firestore dependency in pubspec.yml. One more thing,
you are using latest version, use "FirebaseFirestore" instead of "Firestore".
Go to pubspec.yaml file in your flutter project.
Add this( cloud_firestore: ^0.16.0 ) below dependencies like in the image below.
You can skip this step if you use VScode. It does this automatically if you save the file after the update.
IF NOT , do flutter pub get inside your project. (this fetches the new packages added to the project, in our case cloud_firestore)
Make sure that you are able to see this import in the file you are getting the errors in.
import 'package:cloud_firestore/cloud_firestore.dart';
Next, update Firestore.instance -> FirebaseFirestore.instance in all your files where you are getting this error.
Use this code --
FirebaseFirestore.instance
.collection("users").add({"name": "Majeed"});
change Firestore with FirebaseFirestore and remove the Document and setData
replace setData with add.

I/flutter (31065): No implementation found for method init on channel plugins.flutter.io/google_sign_in

I've been trying to implement google_sign_in library for almost two days now. I have done all necessary configurations from both localhost and the firebase console.
Dependencies:
firebase_analytics: ^5.0.2
firebase_auth: ^0.14.0+5
cloud_firestore: ^0.13.5
flutter_facebook_login: ^3.0.0
mvc_pattern: ^5.0.0
flutter_screenutil: ^0.5.3
google_sign_in: ^4.4.4
Below is the _googleSignUp() custom function.
Future<void> _googleSignUp() async {
try {
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
hostedDomain: '',
clientId: '',
);
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: googleAuth.accessToken, accessToken: googleAuth.idToken);
final FirebaseUser user =
(await _auth.signInWithCredential(credential)).user;
print('Current user: ${user.displayName}');
return user;
} catch (e) {
print(e.message);
}
}
The problem is, whenever I trigger the _googleSignUp() funtion with a button click, I keep getting this log below and then nothing happens.
I/flutter (31065): No implementation found for method init on channel plugins.flutter.io/google_sign_in
Developers how do we fix this? Thank you.
After dealing with this problem for an entire day, I realized the google_sign_in throws that exception if you also have the flutter_facebook_login plugin but haven't configured it as per these instructions.
Nonsensical error message had me going in circles.
Upgrade the flutter_auth plugin to the latest version:
dependencies:
firebase_auth: ^0.16.0
https://pub.dev/packages/firebase_auth#-installing-tab-
What worked for me is changing the AppDelegate.swift file in the ios/Runner folder to:
import UIKit
import Flutter
#UIApplicationMain
#objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}

Flutter Google Login not Getting Registered in Firebase

1. The Problem
I'm trying to implement simple Facebook and Google Sign-in buttons with Firebase and Flutter, however the Google version is acting very weird. When I print the FirebaseAuth.instance.currentUser() I either get errors or prior Facebook login data.
When I login with Facebook, my account does appear on Firebase, however, the Google login seems to do nothing.
Is this something I messed up in the code below or some incompatibility problem with AndroidX with parts of these libraries? Something else?
Also, it is not very clear to me if I have to put the Project public-facing name somewhere inside my project to make the integration with Firebase work (I had to do something similar to setup the Facebook Login button).
2. The Facebook Login
I had to replace logInWithReadPermissions with signInWithCredential because recent versions have changed their API. I've also tried to use previous versions of the packages, but encountered many errors (probably due to AndroidX):
final _auth = FirebaseAuth.instance;
Future<FirebaseUser> _loginWithFacebook () async {
final facebookLogin = FacebookLogin();
final result = await facebookLogin.logInWithReadPermissions(['email']);
if (result.status == FacebookLoginStatus.loggedIn){
final FacebookAccessToken accessToken = result.accessToken;
AuthCredential credential = FacebookAuthProvider.getCredential(
accessToken: accessToken.token,
);
AuthResult signInResult = await _auth.signInWithCredential(credential);
FirebaseUser fbUser = signInResult.user;
return fbUser;
}
else{
return null;
}
}
3. The Google Login
Again, signInWithCredential seems to be the more recent API:
Future<FirebaseUser> _loginWithGoogle () async{
final GoogleSignIn _googleSignIn = GoogleSignIn();
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
AuthResult signInResult = await _auth.signInWithCredential(credential);
final FirebaseUser user = signInResult.user;
print(user);
return user;
}
Edit
I've tried it on an Android 9.0 (Pie) emulator and it still doesn't work.
Apparently, my authentication code was correct for both Google and Facebook, considering the most up-to-date API.
However I needed to integrate a SHA1 Fingerprint to my Firebase environment, which is something I didn't realize I needed to do because none of the tutorials I followed mentioned it and it can be easily dismissed when enabling the Google Sign-in method inside Firebase.
Anyway, here are the steps you will need to complete to get the SHA1 Fingerprint:
Open Command Prompt and cd C:\Program Files\Android\Android Studio\jre\bin.
Get the SHA1 key:
keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
Go to Firebase Console > Project settings > Add Key and add the key.

Resources