Add Firebase Mobile Authentication

authentication

Why we need to add Firebase mobile Authentication in Android Application?

Mobile authentication is much needed nowadays to verify the user authentic information land to remove the fake users and to get the credibility of the user. You can easily track the user by the mobile number and put all checks to you’r system. Someone can put a random number and access you’r data which will hurt you’r business and put you’r data at much higher risk.

1- First you need to add the android app to Firebase Console if not done yet you can get through this from here.

2- Go to Firebase console > Authentication > Sign In Methods and enable phone authentication.

Firebase mobile authentication

You can also add testing numbers for development purpose and the authentication key . So let’s get started on add Firebase mobile authentication android on android studio.

3- For production purpose you also need to add the SHA 1 certificate fingerprints. To get the fingerprints go to project > gradle > project > android > signin reports then you can get the fingerprint from bottom on the screen (optional).

Firebase authentication
Get SHA 1 from android studio

In app build.gradle you need to add.

implementation 'com.google.firebase:firebase-auth:19.3.0'.

Then in MainActivity.java where user enter the mobile number and country code to request the otp.

package com.example.sampleproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
private Helper helper;
private UserModel mUser = new UserModel();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper= new Helper(this);
phoneAuth();
Button bt_login = (Button) findViewById(R.id.bt_login);
final EditText et_mobile_no = (EditText) findViewById(R.id.et_mobile_no);
final EditText et_country_code = (EditText) findViewById(R.id.et_country_code);

bt_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mobile_no = et_mobile_no.getText().toString();
String country_code = et_country_code.getText().toString();
String mobileNumber = country_code+mobile_no;
mUser.setMobile(mobileNumber);

createNewUser(mobileNumber);
}
});
}
private void phoneAuth() {
mAuth= FirebaseAuth.getInstance();

mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
helper.display( "Verification complete" );
String sms_code=credential.getSmsCode();
PhoneAuthCredential credentials = credential;

}

@Override
public void onVerificationFailed(FirebaseException e) {
helper.display(" Verification Failed");
if (e instanceof FirebaseAuthInvalidCredentialsException) {
helper.display("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
helper.display( "Quota exceeded");
}
e.printStackTrace();
helper.hideDialog();
}

@Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
helper.display( "Verification code send");
mUser.setVerificationId(verificationId);

Intent intent = new Intent(MainActivity.this, VerifyOtp.class);
intent.putExtra("user_details", mUser);
intent.putExtra("user_token", token);
startActivity(intent);
helper.hideDialog();


}

@Override
public void onCodeAutoRetrievalTimeOut(String s) {
helper.hideDialog();
super.onCodeAutoRetrievalTimeOut(s);
}
};

}
void createNewUser(String phoneNumber){

PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks

}
}

Now, Verify the opt process in VerifyOtp class.

package com.example.sampleproject;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.Serializable;

public class VerifyOtp extends AppCompatActivity {

private String TAG = "VerifyOtp";
private UserModel mUserModel;
private FirebaseAuth mAuth;
private Helper helper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
mAuth= FirebaseAuth.getInstance();
helper = new Helper(this);
Button bt_submit = (Button)findViewById(R.id.bt_submit);
final EditText et_otp = (EditText)findViewById(R.id.et_otp);
Intent intent = getIntent();

if (intent != null) {

Serializable userSerializable = intent.getSerializableExtra("user_details");

mUserModel = (UserModel) userSerializable;
if(mUserModel!=null) {

}else {

}
}
bt_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String otp = et_otp.getText().toString();

PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mUserModel.getVerificationId(), otp.trim());
signInWithPhoneAuthCredential(credential);
}
});
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
helper.display("Sign in successfully");
final FirebaseUser firebase_user = task.getResult().getUser();
Log.d(TAG, "onComplete: "+firebase_user.getPhoneNumber());
} else {
helper.hideDialog();
helper. display( "Unable to sign in");
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
helper. display("Invalid code");
}
}
}
});
}

}

You can use other sign in methods available in Firebase Authentication.

Also you can download the code from here.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Tagged : / /

One thought on “Add Firebase Mobile Authentication

Leave a Reply

Your email address will not be published. Required fields are marked *