Firebase phone authentication error in Android Studio - android

I'm getting error for phone authentication. I received OTP successfully, but after I share my project with my team member with GitHub, I'm getting this errors.
I also I added MY SHA 1 & SHA 256 in my new firebase console. I also added dependencies, but still I get this error.
I also want to inform that after transfer my project with GitHub, I make new firebase account and add SHA 1 & SHA 256 in this project
Logcat:
03-16 16:19:40.001 8163-8163/com.roundtripride E/zzf: Problem retrieving SafetyNet Token: 7:
03-16 16:19:40.679 8163-8235/com.roundtripride E/FirebaseAuth: [GetAuthDomainTask] Error getting project config. Failed with INVALID_CERT_HASH 400
03-16 16:19:40.713 8163-8163/com.roundtripride E/zzf: Failed to get reCAPTCHA token with error [There was an error while trying to get your package certificate hash.]- calling backend without app verification
03-16 16:19:41.202 8163-8201/com.roundtripride E/FirebaseAuth: [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17093 null
03-16 16:19:41.202 8163-8163/com.roundtripride E/Tag: onVerificationFailed : This request is missing a valid app identifier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or check the logcat for more details.
03-16 16:19:41.202 8163-8163/com.roundtripride E/Tag: onVerificationFailed : This request is missing a valid app identifier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or check the logcat for more details.
03-16 16:19:41.202 8163-8163/com.roundtripride E/Tag: onVerificationFailed : com.google.firebase.auth.FirebaseAuthException: This request is missing a valid app identifier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or check the logcat for more details.
Dependencies:
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:18.0.0'
implementation 'com.google.android.libraries.places:places:2.4.0'
implementation platform('com.google.firebase:firebase-bom:26.7.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-auth:20.0.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
implementation 'com.intuit.sdp:sdp-android:1.0.6'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.amitshekhar.android:jackson-android-networking:1.0.2'
implementation 'com.github.prolificinteractive:material-calendarview:1.6.0'
implementation 'androidx.browser:browser:1.3.0'
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.android.gms:play-services-safetynet:17.0.0'
}
Code:
public class OTPVerifyActivity extends BaseActivity implements View.OnClickListener {
Context context;
private FirebaseAuth mAuth;
private String mVerificationId;
String idToken = "", mobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verify);
Utility.setLoginStatusColor(this);
context = this;
txt_finish = findViewById(R.id.txt_finish);
edt_1 = findViewById(R.id.edt_1);
mAuth = FirebaseAuth.getInstance();
mobile = getIntent().getStringExtra("mobile");
sendVerificationCode();
txt_finish.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == txt_finish) {
Utility.hideSoftKeyboard(edt_1, context);
if (edt_1.getText().toString().equals("")) {
Utility.errDialog("Please enter OTP", context);
} else {
verifyVerificationCode(edt_1.getText().toString().trim());
}
}
}
private void sendVerificationCode() {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91" + mobile) // Phone number to verify
.setTimeout(30L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Log.e("Tag", "get Data : " + phoneAuthCredential.getSmsCode());
Utility.dismissProgressDialog(pd);
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
edt_1.setText(code);
verifyVerificationCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Utility.dismissProgressDialog(pd);
Log.e("Tag", "onVerificationFailed : " + e.getMessage());
Log.e("Tag", "onVerificationFailed : " + e.getLocalizedMessage());
Log.e("Tag", "onVerificationFailed : " + e.toString());
Utility.errDialog(e.getMessage(), context);
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
mVerificationId = s;
Utility.dismissProgressDialog(pd);
}
};
private void verifyVerificationCode(String code) {
//Log.e("Tag","Verify code : "+code);
pd = Utility.showProgressDialog(context);
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code);
signInWithPhoneAuthCredential(credential);
} catch (Exception e) {
Log.e("Tag", "PhoneAuthCredential Exception " + e.getMessage());
}
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(OTPVerifyActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
user.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
idToken = task.getResult().getToken();
Utility.dismissProgressDialog(pd);
Log.e("Tag", "Success OTP " + isDriver);
MyPreference.setPreferenceValue(context,"isLogin","true");
}
}
});
} else {
Utility.dismissProgressDialog(pd);
//verification unsuccessful.. display an error message
String message = "Something is wrong, we will fix it soon...";
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
message = "Invalid code entered...";
}
Log.e("Tag", message);
Utility.errDialog(message, context);
}
}
});
}
}

Remove your debug SHA-1 and SHA-256 from your old firebase account .
Open android studio and click on gradle in right corner > click your project > select app > select tasks > select android > click on signing report > copy our SHA1 and SHA-256 from there.
Add SHA1 and SHA-256 in your new firebase account .(if you are building apk from 2 system add both system's SHA1 and SHA-256).
You need to make sure that you enabled PHONE AUTHENTICATION in Firebase console => Authentication => Sign-in Methods.
Add dependency in build.gradle(:app)
implementation 'androidx.browser:browser:1.3.0'
Go to google cloud console , select your project .
Click on navigation menu and select APis & services and then select Dashboard .
Click on enable api and services and enable api " Android Device Verification".
Download and replace the latest google-services.json file in your project.

implementation 'androidx.browser:browser:1.3.0'
please add this dependency then check sha1 and sha256 one more time then try it

Related

signInAnonymously:FAILURE com.google.firebase.auth.FirebaseAuthException: despite Anonymous Sign in enabled

Despite I have enabled in my Firebase project anonymous sign in, my mobile (Android) app is not able to authenticate and I'm getting this error (on emulator and on physical device too).
signInAnonymously:FAILURE
com.google.firebase.auth.FirebaseAuthException: This operation is restricted to administrators only.
My Firebase config:
My code:
mAuth = FirebaseAuth.getInstance();
...
// Sign in anonymously. Authentication is required to read or write from Firebase Storage.
mAuth
.signInAnonymously()
.addOnSuccessListener(
mActivity,
authResult -> {
Log.d(TAG, "signInAnonymously:SUCCESS");
try {
upload();
} catch (Exception e) {
Log.e(TAG, "upload:FAILURE", e);
}
})
.addOnFailureListener(
mActivity,
exception -> {
Log.e(TAG, "signInAnonymously:FAILURE", exception);
});
}
Dependencies:
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.firebase:firebase-storage:20.0.0'
implementation "com.google.firebase:firebase-core:18.0.2"
Does anybody had the same problem?
Well, in the end, I updated packages to this:
+ implementation platform('com.google.firebase:firebase-bom:29.0.2')
+ implementation 'com.google.firebase:firebase-auth'
+ implementation 'com.google.firebase:firebase-storage'
... implementation "com.google.firebase:firebase-core:18.0.2" //not updated
Make the Firebase storage rules look like this(disclaimer: for my debug version, production I suppose will be more strict):
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
​
And it started to work. But honestly not sure why ¯\(ツ)/¯.

Why FirebaseMessaging getToken() not working?

I made a messaging class extending FirebaseMessagingService and found that onNewToken method was working fine.
But, when I used the sample code for FirebaseMessaging class to get the current Firebase Token, I ran into an error: error: cannot find symbol method getToken().
What am I missing?
Any suggestion would be appreciated.
DataManager.java
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingService;
public class DataManager {
public static String registerGoogleServiceInBackground( final OnDataManagerRegisterGooglePlayServiceListener listener )
{
boolean isEnabledPlayService = true;
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable( getContext() );
{
if( GooglePlayServicesUtil.isUserRecoverableError( resultCode ) )
{
GooglePlayServicesUtil.getErrorDialog( resultCode, (Activity) getContext(), PLAY_SERVICES_RESOLUTION_REQUEST ).show();
} else {
Log.i( "MainActivity.java|checkPlayService", "|This device is not supported.|" );
}
isEnabledPlayService = false;
}
if( isEnabledPlayService )
{
if( TextUtils.isEmpty( registrationId ) )
{
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground( Void... params )
{
String msg;
try {
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(tag, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
registrationId = task.getResult();
}
});
msg = "Device registered, registration ID=" + registrationId;
Log.d("Device registered", "|" + registrationId);
} catch( Exception ex ) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute( String msg ){
if( listener != null ) listener.onFinish( true, registrationId );
Log.i( "MainActivity.java | onPostExecute", "|" + msg + "|" );
}
}.execute( null, null, null );
return "";
}
} else {
if( listener != null ) listener.onFinish( true, registrationId );
return registrationId;
}
} else {
Log.i( "MainActivity.java | onCreate", "|No valid Google Play Services APK found.|" );
if( listener != null ) listener.onFinish( true, registrationId );
return null;
}
}
}
I think it has to do with firebase dependencies versions mismatch. Try to import the BoM for the Firebase platform. By using BoM your app will always use compatible versions of the Firebase Android libraries.
In your app-level build.gradle you can try add the following;
dependencies {
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:28.3.0')
// Declare the dependencies for the Firebase Cloud Messaging and Analytics libraries
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-analytics'
}
You can following the instructions here https://firebase.google.com/docs/cloud-messaging/android/client
Cheers!
I think like handsben above that the problem lies in the dependencies. I have an alternative suggestion that worked for me. This was the error message supplied by android studio
Cannot resolve method 'getToken' in 'FirebaseMessaging'
In the dependencies (in the app-level build.gradle) was this line
implementation 'com.google.firebase:firebase-messaging:20.1.0'
When I clicked on it android studio suggested I change it to
implementation 'com.google.firebase:firebase-messaging:23.0.5'
which I did and the error went away.
Hope this could work for you too

Not instant Remote Config value android?

implementation 'com.google.firebase:firebase-config:11.8.0'
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.fetch(0).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFirebaseRemoteConfig.activateFetched();
String appDefaultColor = mFirebaseRemoteConfig.getString(FIREBASE_REMOTE_CONFIG_DEFAULT_COLOR);
if (appDefaultColor != null && appDefaultColor.length() > 0) {
System.out.println("==== appDefaultColor : " + appDefaultColor);
}
}
}
});
public static String FIREBASE_REMOTE_CONFIG_DEFAULT_COLOR = "project_default_theme_color";
here is my implementation of Firebase remote config.
As above my code explanation, project4_default_theme_color, i get the value from firebase, But the situation is that i change that value from Firebase remote config , but i did't get.
My firebase remote config Key project_default_theme_color and value is #f04030 and Publish Changes.is any wrong in this?
Follow below instruction to resolve this issue
Update your firebase library version
implementation 'com.google.firebase:firebase-config:19.1.0'
implementation 'com.google.firebase:firebase-core:17.2.1'
Initialize FirebaseRemoteConfig
FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
Set firebaseRemoteConfig parameter default value
firebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
Add below code in remote_config_defaults.xml
<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
<entry>
<key>your_key</key>
<value>defaultValue</value>
</entry>
Add this code in your java file
firebaseRemoteConfig.fetch(cacheTimeDuration)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String errorString = "";
if (task.isSuccessful()) {
firebaseRemoteConfig.activate();
errorString = " task is successful ";
} else {
errorString = "task is canceled";
}
Log.i(TAG, "onComplete: error " + errorString);
Log.i(TAG, " Get firebase remote config value " + firebaseRemoteConfig.getString("your_key"));
}
});
Note :
If your Apk is debug then use this method .fetch(cacheTimeDuration)
If your Apk is Release then use this method .fetch()

Google Drive API 403 Forbidden error if i upgrade to Gradle Plugin v3.5.0

I recently updated the Gradle plugin from version 3.4.2 to 3.5.0.
The code to access the list of Drive files has stopped working.
I get: 403 Forbidden domain": "usageLimits", "reason": "dailyLimitExceededUnreg", "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
if I use 3.4.2 it works perfectly again.
// Login
signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(DriveScopes.DRIVE_FILE))
.build();
GoogleSignInClient client = GoogleSignIn.getClient(Backup.this, signInOptions);
startActivityForResult(client.getSignInIntent(), REQUEST_CODE_SIGN_IN);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == REQUEST_CODE_SIGN_IN) {
if (resultCode == Activity.RESULT_OK && resultData != null) {
handleSignInResult(resultData);
}
...
}
super.onActivityResult(requestCode, resultCode, resultData);
}
private void handleSignInResult(Intent result) {
GoogleSignIn.getSignedInAccountFromIntent(result)
.addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
#Override
public void onSuccess(GoogleSignInAccount googleAccount) {
// Use the authenticated account to sign in to the Drive service.
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(Backup.this, Collections.singleton(DriveScopes.DRIVE_FILE));
credential.setSelectedAccount(googleAccount.getAccount());
Drive googleDriveService =
new Drive.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
credential)
.setApplicationName("MyAPP")
.build();
mDriveServiceHelper = new BackupDriveServiceHelper(googleDriveService);
// get info
mDriveServiceHelper.readFileInfo()
.addOnSuccessListener(new OnSuccessListener<Bundle>() {
...
})
.addOnFailureListener(new OnFailureListener() {
...
});
...
}
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
public class BackupDriveServiceHelper {
...
public Task<Bundle> readFileInfo() {
return Tasks.call(mExecutor, new Callable<Bundle>() {
#Override
public Bundle call() throws Exception {
// Retrieve the metadata as a File object.
String pageToken = null;
do {
FileList result = mDriveService.files().list()
.setSpaces("drive")
.setFields("files(id, name, size, modifiedTime, description)")
.setPageToken(pageToken)
.execute(); // <<<<< error 403
...
pageToken = result.getNextPageToken();
} while (pageToken != null);
...
}
});
}
}
I found that while targetting Android 8 (API27) I could get Google Drive to work with Gradle 3.5.0 if I added this to the project gradle.properties
android.enableD8=false
However, after targetting Android 9 (API 28) and replacing android.support.* with androidx.* I get this warning:
The option 'android.enableD8' is deprecated and should not be used anymore.
and the problem returns. It seems to me the D8 DEX compiler is causing the problem, but it can no longer be disabled?
I have filed a bug report for D8
https://issuetracker.google.com/issues/140882055
Update: the solution suggested by Google does indeed work: after adding this to proguard-rules.pro Google Drive works with Gradle 5.4.1 and Plugin 3.5.0
-keepclassmembers class * {
#com.google.api.client.util.Key <fields>;
}

Firebase Authentication API Email/Password Android

I am attempting to write an app for android that uses Firebase Authentication via Email/Password. It is enabled. However the tutorial, and the code in Github for the examples are showing:
private FirebaseAuth mAuth;
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.google.firebase:firebase-core:9.0.2'
}
apply plugin: 'com.google.gms.google-services'
However, I get an error as if the "FirebaseAuth" doesn't exist. However the latest documentation says otherwise.
Github sample code
Any help would be greatly appreciated.
Replace the com.google.firebase:firebase-core:9.0.2' dependency with the com.google.firebase:firebase-auth:9.0.2 dependency. So:
compile 'com.google.firebase:firebase-auth:9.0.2'
instead of
compile 'com.google.firebase:firebase-core:9.0.2' under your dependencies.
I did not find the FirebaseAuth class in the core dependency but I did find it in the auth dependency. Furthermore, if you checkout their dependencies list, they do not add the core dependency, they add the auth dependency instead.
According to documentation in the firebase web page you should create a Firebase object using the URL from your firebase and from there create usernames with passwords or log them in. The code you showed used this FirebaseAuth for that.
Here is the code to create a new user:
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.createUser("bobtony#firebase.com", "correcthorsebatterystaple", new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
}
#Override
public void onError(FirebaseError firebaseError) {
// there was an error
}
});
Here is the code to log him in:
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithPassword("bobtony#firebase.com", "correcthorsebatterystaple", new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
}
});
Got all of this info from the quick start guide here: https://www.firebase.com/docs/android/guide/login/password.html#section-logging-in
Hope it helps.

Categories

Resources