I'm using Firebase Phone Authentification to verify users accounts. When I try to authenticate with a wrong verification code, I get an IllegalArgumentException. Is there any way to fix that without using try catch blocks?
Here is the exception message :
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, or temporaryProof.
at com.google.android.gms.common.internal.zzbq.checkArgument(Unknown Source)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source)
at com.example.myApp.testFragment$3$4.onClick(testFragment.java:316)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
And here is the line where I get the error :
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCode, inputCode);
I'm intentionally using wrong verification code in inputCode and hoping to get an error message instead of the exception.
It returns an exception so the aim should be to catch the exception it throws in the debug console. I do that by wrapping the portion of that code in a try catch and Toast it out for the user of the aim to see rather than the usual crash which isnt visible to the End Users.
Like this...
private void verifyCode(String code) {
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}catch (Exception e){
Toast toast = Toast.makeText(this, "Verification Code is wrong", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
}
Calls to PhoneAuthProvider.getCredential(...) return a PhoneAuthCredential object, which is defined as:
Wraps phone number and verification information for authentication purposes.
So getCredential() cannot return an error message. Instead it throws an exception if there is a problem with the verification/credential information you provided.
I was getting same issue and resolved it. actually you need to check verificationId and code is not null
Thanks.
I got the same error, just add the SHA certificates. Error will dissolved.
Related
I'm building an app where I store app data in the app-specific-folder on Google Drive. I've been able to setup everything related to file storage and retrieval. The problem I'm facing is regarding permissions. The user has an option to disconnect the app from the Google Drive settings panel.
I use the DriveScopes.DRIVE_APPDATA meaning https://www.googleapis.com/auth/drive.appdata scope to save data.
I'm trying to figure out how to find out if this has happened on the app side. If I try to continue using the drive related apis, with the app being disconnected, then it crashes with a UserRecoverableAuthException.
com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:297)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:476)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:409)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:526)
at abhiank.maplocs.ui.drivesync.DriveSyncService.onHandleIntent(DriveSyncService.kt:68)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:78)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:67)
Caused by: com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission
at com.google.android.gms.auth.zze.zzb(Unknown Source:13)
at com.google.android.gms.auth.zzd.zza(Unknown Source:77)
at com.google.android.gms.auth.zzd.zzb(Unknown Source:20)
at com.google.android.gms.auth.zzd.getToken(Unknown Source:7)
at com.google.android.gms.auth.zzd.getToken(Unknown Source:5)
at com.google.android.gms.auth.zzd.getToken(Unknown Source:2)
at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source:55)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:267)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:292)
I tried the following to figure out if the app does not have the permissions or scopes.
Look at data inside GoogleSignInAccount instance received from GoogleSignIn.getLastSignedInAccount(this). This had the following scopes available in account.grantedScopes() after app had been disconnected. drive.appdata is shown even though app is disconnected.
[https://www.googleapis.com/auth/drive.appdata, https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email, openid, profile, email]
Last thing I tried was hasPermissions method available in GoogleSignIn. I checked if the APP_DATA scope was available with this call and it returned true. So no help there either.
GoogleSignIn.hasPermissions(account, Scope(DriveScopes.DRIVE_APPDATA))
I'm really stuck now. Any help will be really appreciated. Thanks.
I ended up using a try-catch around my drive related code and catching the UserRecoverableAuthIOException. According to the documentation, this is called when -
UserRecoverableAuthExceptions signal Google authentication errors that
can be recovered with user action, such as a user login.
This has worked decently well for me. Considering the fact that this question has not received any other answers in 2 years, there doesn't seem to be any method to fetch the information about whether the app is disconnected or not via an API or SDK call.
Here's the code I use
fun getGoogleDriveService(context: Context): Drive {
val credential = GoogleAccountCredential.usingOAuth2(context, setOf(DriveScopes.DRIVE_APPDATA))
credential.selectedAccount = GoogleSignIn.getLastSignedInAccount(context)!!.account
return Drive.Builder(NetHttpTransport(), GsonFactory(), credential)
.setApplicationName(DriveSyncService.APP_NAME)
.build()
}
try {
val driveService = getGoogleDriveService(this)
var fileList = driveService.files().list().execute()
//...
//more code
} catch (e: UserRecoverableAuthIOException) {
/*
Doing a sign-out on the googleSignInClient so that there is no mismatch
in sign-in state and so that when I start sign-in process again, it
starts afresh
*/
googleSignInClient.signOut()
/*
Then I show a pop up telling user that app was disconnected and
to sign in again. And then on click I start the sign-in flow again.
*/
} catch (e: GoogleJsonResponseException) {
//https://googleapis.dev/java/google-api-client/latest/index.html?com/google/api/client/googleapis/json/GoogleJsonResponseException.html
//404 is file being updated/deleted was not found
if (e.message != null && e.message!!.contains("storageQuotaExceeded")) {
//todo handle storage exceeded error. Inform user
}
} catch (e: IOException) {
//todo handle network error
}
I get following error frequently when I try to sign in silently on android. How can I debug this. What is the reason for this. (I have an active google account on my android phone.)
signInSilently(): failure
com.google.android.gms.common.api.ApiException: 4:
at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source)
at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source)
at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source)
at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source)
at com.google.android.gms.auth.api.signin.internal.zzg.zza(Unknown Source)
at com.google.android.gms.auth.api.signin.internal.zzt.onTransact(Unknown Source)
at android.os.Binder.execTransact(Binder.java:446)
the code is follows
mGoogleSignInClient.silentSignIn().addOnCompleteListener(activity,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInSilently(): success");
onConnected(task.getResult());
} else {
Log.d(TAG, "signInSilently(): failure", task.getException());
Toast.makeText(activity, "A sign-in problem encountered.",
Toast.LENGTH_SHORT).show();
onDisconnected();
}
}
});
There is a list of error codes
According to it, your error code means following:
public static final int SIGN_IN_REQUIRED
The client attempted to connect to the service but the user is not signed in. The client may choose to continue without using the API. Alternately, if hasResolution() returns true the client may call startResolutionForResult(Activity, int) to prompt the user to sign in. After the sign in activity returns with RESULT_OK further attempts should succeed.
Constant Value: 4
It means, that user needs to login manually before you can use silentSignIn. You can find an example on Google github
That error happened to me because I haven't added the email I was testing with to the Testers tab in Google Play Games Console.
I believe it also occurs if your build hasn't been signed with the same SHA1 key that your google play games app id was generated with
I am trying to add user details to Firestore db, but can't write data in it.
Actually none of the listeners are triggered neither onSuccess() nor onFailure().
here is my code.
Map<String,Object> userlol = new HashMap<>();
userlol.put("name",name);
userlol.put("email",email);
userlol.put("uid",currentUser.getUid());
Log.d(TAG, "we are here");
CollectionReference dc = db.collection("users");
DocumentReference dd = dc.document(currentUser.getUid());
dd.set(userlol)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(SignupActivity.this, "User Added" ,
Toast.LENGTH_SHORT).show();
Log.d(TAG,"User added to database");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignupActivity.this, "ERROR" +e.toString(),
Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
There is no toast nor the Log in my logcat.I can see
D/logging: we are here
This log and logs after this method.
There is no issue with rules as onFailure() is also not working.
I have searched every possible thing but nothing worked.
The only way I can get neither of the callbacks to trigger is when there is no network connection on my device. In that case the behavior makes sense, since the task is only considered completed when the data has been committed (or rejected) on the server.
To easily see if the Firestore client indeed can't connect to the server, enable debug logging:
FirebaseFirestore.setLoggingEnabled(true);
I see log entries like this after doing so:
11-12 07:56:21.366 10034-10066/com.firebase.firestorestackoverflow I/Firestore: (0.6.6-dev) [zzetk]: (b6322ac) Stream closed with status: zzcd{code=UNAVAILABLE, description=null, cause=java.net.UnknownHostException: Unable to resolve host "firestore.googleapis.com": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:470)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at io.grpc.internal.zzbj$zzb.zztu(Unknown Source)
at io.grpc.internal.zzbk.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.android_getaddrinfo(Native Method)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at io.grpc.internal.zzbj$zzb.zztu(Unknown Source)
at io.grpc.internal.zzbk.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
}.
well for anyone having that problem in the future just Uninstall your application and reinstall it, as savage as it seams it works(y)
I had the same problem.
First of all turning on the logs helped a lot as #Frank van Puffelen suggested.
In my case I got "The Cloud Firestore API is not available for Datastore Mode projects".
So I went to GCP and created manually a collection by changing the db to a native one. And then I had an option on the gui.
Now the error changed to "FirebaseFirestoreException: permission_denied: missing or insufficient permissions"
So I changed the permissions under the "rules" tab in firestore.
And that fixed it for me :)
I guess the problem was the permissions from the beginning, but I can't tell for sure now.
I had the same error. In my case, I was creating a user and automatically logging him/her out, for them to log manually.
I removed the sign out, as data appears not to be written if there is no user logged in.
Do you have a user signed in when the data is written? Creating a user signs him/her in automatically.
Hope it helps!
It appears that just like after adding new permissions in the manifest file, the app has to be reinstalled to register the changes. I tried reinstalling the app after adding the firestore connection and everything worked fine. voila!
I've followed AWS Mobile Hub push integration guide, and integrated AWS SNS push services in my app. When I open the app I get this error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.intap.appme, PID: 23576
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.intap.name/com.intap.name.MainActivity}: com.amazonaws.AmazonServiceException: 1 validation error detected: Value null at 'token' failed to satisfy constraint: Member must not be null (Service: AmazonSNS; Status Code: 400; Error Code: ValidationError; Request ID: 21d6a3b2-0459-513a-bf7a-f3c1d99d41ac)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: com.amazonaws.AmazonServiceException: 1 validation error detected: Value null at 'token' failed to satisfy constraint: Member must not be null (Service: AmazonSNS; Status Code: 400; Error Code: ValidationError; Request ID: 21d6a3b2-0459-513a-bf7a-f3c1d99d41ac)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:712)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:388)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:199)
at com.amazonaws.services.sns.AmazonSNSClient.invoke(AmazonSNSClient.java:2262)
at com.amazonaws.services.sns.AmazonSNSClient.createPlatformEndpoint(AmazonSNSClient.java:447)
at com.amazonaws.mobile.push.PushManager.subscribeToTopic(PushManager.java:264)
at com.intap.name.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
The code lines mentioned in the app are those lines:
PushManager.java:264 (The whole method)
public void subscribeToTopic(final SnsTopic topic) {
final CreatePlatformEndpointRequest endpointRequest = new CreatePlatformEndpointRequest();
endpointRequest.setPlatformApplicationArn(platformApplicationArn);
try {
endpointRequest.setToken(InstanceID.getInstance(context).getToken(sharedPreferences.getString("deviceToken", ""), GoogleCloudMessaging.INSTANCE_ID_SCOPE));
} catch (IOException e) {
Log.e("Error", e.getMessage());
}
/* This is line 264 -> */ final CreatePlatformEndpointResult endpointResult = sns.createPlatformEndpoint(endpointRequest);
final SubscribeRequest request = new SubscribeRequest();
request.setEndpoint(endpointResult.getEndpointArn());
request.setTopicArn(topic.getTopicArn());
request.setProtocol(SNS_PROTOCOL_APPLICATION);
final SubscribeResult result = sns.subscribe(request);
// update topic and save subscription in shared preferences
final String subscriptionArn = result.getSubscriptionArn();
topic.setSubscriptionArn(subscriptionArn);
sharedPreferences.edit().putString(topic.getTopicArn(), subscriptionArn).apply();
}
MainActivity.java:50
pushManager.subscribeToTopic(pushManager.getDefaultTopic());
When I'm trying to send a push message through the online Firebase console, The device gets the push messages, and when I click on the message to open the app it keeps crashing.
When I'm trying to send a push message through the online SNS console, I don't get any push notfiications, which means the error is in the registration to SNS.
How can I solve it? I have no idea about it...
The token is coming back as null from Google's SDK. The reason is due to this line:
endpointRequest.setToken(InstanceID.getInstance(context)
.getToken(sharedPreferences.getString("deviceToken", ""),
GoogleCloudMessaging.INSTANCE_ID_SCOPE));
The first parameter to getToken() should be the GCM Sender ID rather than the device token that is being passed as pulled from sharedPreferences. Changing your code to pass the sender ID as follows, should fix the issue:
endpointRequest.setToken(InstanceID.getInstance(context)
.getToken(gcmSenderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE));
Also, it appears that the code you pasted was modified from a Mobile Hub project that was generated in the fairly distant past. There have been improvements in the PushManager since then. The latest versions generated by the Mobile Hub would use the GCMTokenHelper class, which is not present in the code you pasted. Please try generating the sample app or SDK using the Mobile Hub again and updating your app to use the more recently generated code and report back if you are still experiencing issues.
Android Firebase Google signin through authorization error when google return token id. i have both cleint id as well as web sdk key saved on firebase. Even json file.
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(OnBoarding.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
Got this error
com.google.firebase.FirebaseException: An internal error has occured. [ Bad Request ]
at com.google.android.gms.internal.zzacq.zzbN(Unknown Source)
at com.google.android.gms.internal.zzacn$zzg.zza(Unknown Source)
at com.google.android.gms.internal.zzacy.zzbO(Unknown Source)
at com.google.android.gms.internal.zzacy$zza.onFailure(Unknown Source)
at com.google.android.gms.internal.zzact$zza.onTransact(Unknown Source)
at android.os.Binder.execTransact(Binder.java:565)
Though google signIn went well there is something missing with firebase which m not able to figure out need help
Logs
"error": {
"errors": [{
"domain": "usageLimits",
"reason": "keyExpired",
"message": "Bad Request"
}],
"code": 400,
"message": "Bad Request"
}
}
In the firebase console (Overview) Under Your mobile apps click the overflow button (three vertical dots) and goto Manage.
Once there goto your app and download the google-services.json
Add that to the root directory of your app and also to the /app folder.
This worked for me to fix this exact error. I assume I changed something at some point and needed a new one.
Hopefully this helps. Goodluck
Some reason to get [ Bad Request ].
Error Conditions:
The Firebase REST API will return error codes under these circumstances.
1) 404 Not Found : A request made over HTTP instead of HTTPS
2) 400 Bad Request : Unable to parse PUT or POST data
3) 400 Bad Request : Missing PUT or POST data
4) 400 Bad Request : Attempting to PUT or POST data which is too large
5) 417 Expectation Failed : A REST API call that doesn't specify a Firebase name
6) 400 Bad Request : A REST API call that contains invalid child names as part of the path
7) 403 Forbidden : A request that violates your Security and Firebase Rules
Check which type of parameter or other things are missing in request as per above option.
I hope its helps you.