Flutter Firebase Auth doesn't work from Google Play - android

I've firebase auth services in my flutter app. It's working on emulator & real device (while debug). But when i publish it on google play neither alpha test or release version it doesn't work.
Main.dart
StreamProvider(
create: (context) => context.read<AuthenticationService>().authStateChanges,
)
AuthService
final FirebaseAuth _firebaseAuth;
AuthenticationService(this._firebaseAuth);
AccessToken accessToken;
Stream<User> get authStateChanges => _firebaseAuth.idTokenChanges();
SignedIn Method in AuthService
Future<String> signIn({String email, String password}) async {
try {
await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
String uid = await FirebaseAuth.instance.currentUser.uid;
return "Signed in";
} on FirebaseAuthException catch (e) {
return e.message;
}
}
Login.dart
var login = await context.read<AuthenticationService>().signIn(email: mailController.text, password: sifreController.text);

It could be that you forgot to put the Google Play fingerprint into your Firebase App configuration.
If the Google Play fingerprint are not present on your app, there is no way for the user to connect to Firebase services.
You can find your Google play fingerprint into the Setup -> App Signing menu.
See the picture below
You should then add them in the android settings of your firebase app.

Related

flutter google signin stuck loading after select account

i am trying to sign in with google first my info i chose google account it stuck in loading without any response or even any console message realted to it here is my code
GoogleSignInAccount _currentUser;
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/cloud-platform.read-only',
],
);
#override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
setState(() {
_currentUser = account;
});
});
_googleSignIn.signInSilently();
}
Future<void> _googlelogin() async {
try {
final GoogleSignInAccount googleSignInAccount =
await _googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
} catch (error) {
print(error);
}
}
....
RaisedButton(
onPressed: () {
_googlelogin();
},),
),
preview of what happening
preview of messages in console if it related
Make sure that you are requesting only information of the scopes you are allowed to access.
In my case, I copied the following example and didn't notice that I don't have access to contacts.
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
Changing to the following worked for me.
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
],
);
I deleted the app on firebase console, created new.
I added SHA-1, SHA256 fingerprints in firebase project-level settings.
I also selected my email-id on "Support email" field in project-level settings.
I had com.google.gms:google-services on build.gradle as suggested by #Abdelazeem.
None of them worked for me. Every time I select my Gmail account, it kept loading indefinitely and nothing significant was printed in the console either.
But this worked for me:
pubspec.yaml
dependencies:
firebase_core: ^1.7.0
firebase_auth: ^3.1.2
googleapis: ^5.0.1
google_sign_in: ^5.1.1
AuthenticationService.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:googleapis/drive/v3.dart' as drive;
import 'package:google_sign_in/google_sign_in.dart' as signIn;
class AuthenticationService {
signIn.GoogleSignInAccount? account;
Future<User?> authenticate() async {
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
final signIn.GoogleSignIn googleSignIn =
signIn.GoogleSignIn.standard(scopes: [drive.DriveApi.driveFileScope]);
account = await googleSignIn.signIn();
if (account != null) {
final signIn.GoogleSignInAuthentication googleSignInAuthentication =
await account!.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
try {
final UserCredential userCredential =
await auth.signInWithCredential(credential);
user = userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == 'account-exists-with-different-credential') {
// handle the error here
} else if (e.code == 'invalid-credential') {
// handle the error here
}
} catch (e) {
// handle the error here
}
}
return user;
}
}
i just reset everything and delete firebase project and recreate it from scratch again and magically everything work
Make sure you added those two lines to your app/build.gradle:
apply plugin: 'com.google.gms.google-services' //<== first line
dependencies {
implementation 'com.google.android.gms:play-services-auth:19.2.0' //<== second line
...
Also, add to your root/build.gradle inside buildscript.dependencies
classpath 'com.google.gms:google-services:4.3.5'
If you didn't register your app on firebase then go ahead and once you're done, make sure you downloaded the google-services.json file and put it inside your android/app directory.
if Your app is marked as "EXTERNAL" on "OAuth consent screen" - you need to add tester Users
If your API project's publishing status is 'Production', some API scopes require verification by Google before they may be presented to the user in a consent screen. Since they are kind of sensitive or restricted scopes.
If your API project's publishing status is 'Testing', you need to add test users according to AYMAN's answer.

Expo React Native google auth with firebase not working in published apk version on android

I wanted to include google Auth in my app but it is not working in the published version on android even though it worked with expo
Here is the code:
logInGoogle = async () => {
try {
const result = await Google.logInAsync({
androidClientId:ID,
iosClientId:ID,
scopes: ["profile", "email"],
behavior:'web'
});
if (result.type === "success") {
const { idToken, accessToken } = result;
const credential = GoogleProvider.credential(idToken, accessToken);
Firebase
.auth()
.signInWithCredential(credential)
.then(function(result){
if(result.additionalUserInfo.isNewUser){
Firebase.database().ref('UserToQuestion/' + Firebase.auth().currentUser.uid).set({
notifier: {
Email:Firebase.auth().currentUser.email
}
})
}
})
.catch(error => {
Alert.alert(error)
console.log("firebase cred err:", error);
});
} else {
return { cancelled: true };
}
} catch (err) {
console.log("err:", err);
}
}
Here is my app.json for android
"android": {
"package": "com.aparson.SFS",
"versionCode": 1
},
In the google console, I have a working service account but I have not configured the OAuth consent screen, but I am not sure if that is the problem because when I click the button for google login nothing happens at all. I have also changed the SHA-1 certificate to what the app signing showed which is what someone said to do in a different question but that did not work either.
I would appreciate it if anyone could help.
Thanks
you should use expo-google-sign-in
expo-google-sign-in provides native Google authentication for standalone Expo apps or bare React Native apps. It cannot be used in the Expo client as the native GoogleSignIn library expects your REVERSE_CLIENT_ID in the info.plist at build-time. To use Google authentication in the Expo client, check out expo-google-app-auth or expo-app-auth.
https://docs.expo.io/versions/latest/sdk/google-sign-in/#googleidentity

React Native Google Signin with multiple accounts

I have a react native application which uses google sign in. currently, I can sign in with one of my google accounts which my mobile signed in, but I need to do an OAuth for another google account in my google accounts stack, this is to get the API access I need the serverAuthToken for the secondary accounts
The library I'm using for google login - https://github.com/react-native-community/google-signin
What I have done till now:
const firebaseGoogleLogin = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
if (userInfo) {
await storeToken(userInfo);
// eslint-disable-next-line no-console
console.log('User info retrieved during login', userInfo);
}
// create a new firebase credential with the token
// eslint-disable-next-line max-len
const credential = firebase.auth.GoogleAuthProvider.credential(userInfo.idToken, userInfo.accessToken);
// login with credential
// eslint-disable-next-line no-unused-vars
const firebaseUserCredential = await firebase.auth().signInWithCredential(credential);
console.log('Logged in')
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log('sign in cancelled', error);
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log('signin in progress error', error);
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log('play services are not available or outdated', error);
} else {
console.log('some other error occurred', error);
}
}
};
Result for the above code:
This is the code I used to login with my primary Google account, after logging in I'm triggering the play services modal to sign in with other accounts using the above, but the modal closes with loading a sec and gets closed, shows me Logged in in the log, since I have already logged, in the play services automatically bypass the option to select an account
The above problem occurs only in android, ios seems fine even after logging in with an account
Was trying to do a hack if there isn't a way for multiple account authorization since an account already signed in it is bypassing the play service modal, I'm thinking to logout the user once he signed into my application (process level) and inside the main activity, I can have the play services still? is this the right way to do!
Probably you have fixed the issue. I think the method below will solve your problem. Call this after logout.
signOut = async () => {
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
this.setState({ user: null }); // Remember to remove the user from your app's state as well
} catch (error) {
console.error(error);
}
};
First import { GoogleSignin } from "#react-native-google-signin/google-signin"; in your logout file
If you're using firbase authentication after
auth().signOut().then(() => {
GoogleSignin.revokeAccess();
});

Developer Error while logging in with google in react-native + firebase

I am trying to log in with google in my project build in react-native. I am testing it on a real android device. But it is giving DEVELOPER ERROR while signing in. I have added the SHA 1 certificate of the debug.keystore formed in android/app directory of the project to the project setting in firebase console.
ERROR:
This is the error image
The following is how I am implementing it.
import { GoogleSignin } from '#react-native-community/google-signin';
import auth from '#react-native-firebase/auth';
const GoogleLogin = () => {
useEffect(() => {
GoogleSignin.configure({
webClientId: '************************', // From Firebase Console Settings
});
}, [])
async function onGoogleButtonPress() {
console.log('i am running on google login function')
// Get the users ID token
const { idToken } = await GoogleSignin.signIn();
console.log('idToken :', idToken)
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
}
const handleSignIn = () => {
onGoogleButtonPress()
.then(() => {
console.log('Signed in with google.')
})
.catch((err) => console.log('error while signing in with Google:', err))
}
return (
<Button
title="Google Sign-In"
onPress={handleSignIn}
/>
)
}
In handleSignIn method, it is going in .catch.
Any help is appreciated
Try also passing in the accessToken.
See https://firebase.google.com/docs/reference/node/firebase.auth.GoogleAuthProvider#credential.
At least one of ID token and access token is required.
async function onGoogleButtonPress() {
console.log('i am running on google login function')
// Get the users ID token
const { idToken, accessToken } = await GoogleSignin.signIn();
console.log('idToken :', idToken, 'accessToken :', accessToken)
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken, accessToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
}

firebase phone authentication problem in flutter

I am using below code for firebase authentication.
void NavigateToOtp(){
//Navigate to another screen
}
Future<void> verifyPhone() async {
final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
this.verificationId = verId;
};
try {
await _auth.verifyPhoneNumber(
phoneNumber: '+XX XXXXXXXXXX', // PHONE NUMBER TO SEND OTP
codeAutoRetrievalTimeout: (String verId) {
//Starts the phone number verification process for the given phone number.
//Either sends an SMS with a 6 digit code to the phone number specified, or sign's the user in and [verificationCompleted] is called.
this.verificationId = verId;
},
codeSent:
smsOTPSent, // WHEN CODE SENT THEN WE OPEN DIALOG TO ENTER OTP.
timeout: const Duration(seconds: 20),
verificationCompleted: (AuthCredential phoneAuthCredential) {
print(_auth.currentUser());
print(phoneAuthCredential);
NavigateToOtp();
},
verificationFailed: (AuthException exceptio) {
print('${exceptio.message}');
});
} catch (e) {
handleError(e);
}
}
void sendOtp(){
verifyPhone();
}
But is showing me below error :
[FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq#847da6d
I am using Android emulator Pixel API 29.
Added phone number in Google-sign and enable phone signin providers in firebase console
Also created SHA key and also added google firebase plugin in .gradle file
I am using this code : https://www.c-sharpcorner.com/article/otp-authentication-in-flutter-using-firebase/
In the new Firebase auth version, they've made major changes like Recaptcha for human verification.it needs a browser to verify so, Add below dependency to your build.gradle file
implementation 'androidx.browser:browser:1.3.0'
This will help firebase to open the browser for a reCAPTCHA verification.

Categories

Resources