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);
}
Related
I am using App Check with my Flutter Android debug App to validate my app with my Cloud Run Node API. I followed the steps required to get and add the debug token to the Firebase Console Admin UI but it is rejecting my requests.
Here is my backend code:
const authenticate = async (req, res, next) => {
const appCheckToken = req.header('X-Firebase-AppCheck');
if (!appCheckToken) {
res.status(401);
return next('Unauthorized');
}
try {
const appCheckClaims = await firebaseAdmin.appCheck().verifyToken(appCheckToken);
// If verifyToken() succeeds, continue with the next middleware
// function in the stack.
return next();
} catch (err) {
res.status(401);
return next('Unauthorized');
}
}
And my main method in Flutter:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FirebaseAppCheck.instance.activate(
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
// Default provider for Android is the Play Integrity provider. You can use the "AndroidProvider" enum to choose
// your preferred provider. Choose from:
// 1. debug provider
// 2. safety net provider
// 3. play integrity provider
androidProvider: AndroidProvider.debug,
);
runApp(const MyApp());
}
I hope you are doing well.
I have a problem when I connect with google on the emulator with android.
If I go through Expo Go on either Android or Ios, it works fine. But when I build my apk, and I install it on the emulator it sends me back to the same login page without redirecting me to the application.
Do you have an idea of the origin of the problem?
My google login function :
try {
const result = await promptAsync();
if (result.type === "success") {
/* `accessToken` is now valid and can be used to get data from the Google API with HTTP requests */
const { id_token } = result.params;
const provider = new firebase.auth.GoogleAuthProvider();
const credential =
firebase.auth.GoogleAuthProvider.credential(id_token);
auth.signInWithCredential(credential)
.then((res) => {
const user = res.additionalUserInfo.profile;
let action = addUserOnFirestore(
res.user?.uid,
user.email,
user.given_name,
user.family_name,
user.picture,
res
);
setIsLoading(true);
try {
dispatch(action);
} catch (err) {
setError(err.message);
}
setIsLoading(false);
})
.catch((error) => {
console.log("firebase cred err:", error);
});
} else {
console.log("cancelled");
}
} catch (e) {
console.log("general error : ", e);
return { error: true };
}
}
And the properties define :
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId: "XXXX",
iosClientId: "XXX",
androidClientId: "XXX",
androidStandaloneAppClientId: "XXX",
redirectUri: Platform.select({
// iOS handles redirectUri perfectly fine on it's own
ios: undefined,
// Due to Expo's bug, we need to manually encode the redirectUri
// https://github.com/expo/expo/issues/12044
android: makeRedirectUri({
// intent filter set up in app.config.js
// must be the same as "package name" in Google Cloud Console
native: 'packagename://oauthredirect',
}),
})
});
Thanks in advance for your responses.
I'm using firebase auth for phone number verification in my flutter project, it works fine as it sends the OTP code to the device but verificationcompleted method which autoverifies the phone number does not call at all. I have followed all the configuration setups, Device verification api is enabled in Google cloud console. Now i am not sure if the firebase removed this autoverified or not because i did not find anything about it in their documentaion,
Here is the code to get OTP Code.
Future getPinCode() async {
print("Starting OTP process");
_auth.verifyPhoneNumber(
phoneNumber:
"+92${phoneNumber.toString()}",
timeout: const Duration(seconds: 60),
verificationCompleted: _verificationCompleted,
verificationFailed: _verificationFailed,
codeSent: _codeSent,
codeAutoRetrievalTimeout: _codeAutoRetrievalTimeout,
);
}
_verificationCompleted(PhoneAuthCredential authCredential) {
log("verificationCompleted ");
_auth.signInWithCredential(authCredential).then((UserCredential result) {
Get.to(() => const HomePage());
}).catchError((e) {
log(e);
});
}
here in verificationcompleted Im signing user and navigating to homePage, but this method never gets called
_verificationFailed(FirebaseAuthException authException) {
print(authException.message);
}
_codeSent(String verificationId, int? resendToken) async {
log("codeSent $verificationId");
verificationCode =
verificationId; // Update the UI - wait for the user to enter the SMS code
//String smsCode = 'xxxx';
// Create a PhoneAuthCredential with the code
//PhoneAuthCredential credential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: smsCode);
// Sign the user in (or link) with the credential
//await _auth.signInWithCredential(credential);
}
_codeAutoRetrievalTimeout(String verificationId) {
verificationCode = verificationId;
log("Timout");
}
output Log (1)
output Log (2)
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.
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();
});