Firebase: Sign-In Authentication Using Phone Number FIREBASE

Firebase: Sign-In Authentication Using Phone Number  

Firebase: Sign-In Authentication Using Phone Number

Sign-In Authentication Using Phone Number

We can use Firebase authentication to the sign-in user by sending a text message to the user's phone. The user will sign-in using a one-time code that they have received in their message box.

Starting steps are the same, such as creating a Firebase project, creating an Android Studio project, adding firebase to our Android app, adding firebase-auth and firebase-core dependencies, adding SHA-1 and SHA-256 keys, add JSON file, and apply plugins. for reference first read Firebase: Google Sign-In Authentication or Firebase: Facebook Sign-In Authentication.

The next steps are to enable phone number authentication in Firebase console. After these preliminary steps, we have to perform the following steps:

Step1:

Now, we will add permission to use the Internet in our Manifest file.

Step2:

Now, we will modify our 'activity_main.xml' file for phone number authentication. The layout design will be as followed:

Step3:

Now, add code for the phone number authentication. and modify your 'MainActivity.java' file. Below is the code for the phone number authentication.

 

  1. //Implementing onClickListener  
  2. public class MainActivity extends AppCompatActivity implements View.OnClickListener {  
  3.       
  4.     private static final String TAG = "PhoneAuthActivity";  
  5.   
  6.     //Adding a member variable for the key verification in progress  
  7.     private static final String KEY_VERIFY_IN_PROGRESS = "key_verify_in_progress";  
  8.   
  9.     //Creating FirebaseAuth member variable  
  10.     private FirebaseAuth mAuth;  
  11.   
  12.     //Adding a bunch of member variables for view groups, edit text, and buttons.  
  13.     private ViewGroup mPhoneNumberViews;  
  14.     private ViewGroup mSignedInViews;  
  15.   
  16.     private EditText mPhoneNumberField;  
  17.     private EditText mVerificationField;  
  18.   
  19.     private Button mStartButton;  
  20.     private Button mVerifyButton;  
  21.     private Button mResendButton;  
  22.     private Button mSignOutButton;  
  23.       
  24.     //Setting Boolean to say whether or not we are in progress.   
  25.     private boolean mVerificationInProgress = false;  
  26.   
  27.     //Adding verification id as a member variable.   
  28.     private String mVerificationId;  
  29.       
  30.     //Adding a member variable for PhoneAuthProvider.ForceResendingToken callback.   
  31.     private PhoneAuthProvider.ForceResendingToken mResendToken;  
  32.       
  33.     //Adding a member variable for a callback which is our PhoneAuthProvider.OnVerificationStateChangeCallbacks.  
  34.     private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;  
  35.   
  36.     @Override  
  37.     protected void onCreate(Bundle savedInstanceState) {  
  38.         super.onCreate(savedInstanceState);  
  39.   
  40.         setContentView(R.layout.activity_main);  
  41.   
  42.         // Restoring the instance state  
  43.         if (savedInstanceState != null) {  
  44.             onRestoreInstanceState(savedInstanceState);  
  45.         }  
  46.   
  47.         // Assigning all the views  
  48.         mPhoneNumberViews = findViewById(R.id.phoneAuthFields);  
  49.         mSignedInViews = findViewById(R.id.signedInButtons);  
  50.   
  51.         mPhoneNumberField = findViewById(R.id.fieldPhoneNumber);  
  52.         mVerificationField = findViewById(R.id.fieldVerificationCode);  
  53.   
  54.         mStartButton = findViewById(R.id.buttonStartVerification);  
  55.         mVerifyButton = findViewById(R.id.buttonVerifyPhone);  
  56.         mResendButton = findViewById(R.id.buttonResend);  
  57.         mSignOutButton = findViewById(R.id.signOutButton);  
  58.   
  59.         // Setting all the click listeners  
  60.         mStartButton.setOnClickListener(this);  
  61.         mVerifyButton.setOnClickListener(this);  
  62.         mResendButton.setOnClickListener(this);  
  63.         mSignOutButton.setOnClickListener(this);  
  64.   
  65.   
  66.         // Initialize Firebase Auth  
  67.         mAuth = FirebaseAuth.getInstance();  
  68.   
  69.         // Initializing phone auth callbacks  (For verification, Not entering code yet, To get text send to device)  
  70.         mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {  
  71.   
  72.             @Override  
  73.             public void onVerificationCompleted(PhoneAuthCredential credential) {  
  74.                 // It will be invoked in two situations, i.e., instant verification and auto-retrieval:  
  75.                // 1 - In few of the cases, the phone number can be instantly verified without needing to  enter or send a verification code.  
  76.               // 2 - On some devices, Google Play services can automatically detect the incoming verification SMS and perform verification without  
  77.               //     user action.  
  78.                 Log.d(TAG, "onVerificationCompleted:" + credential);  
  79.                 mVerificationInProgress = false;  
  80.   
  81.                 //Calling signInWithPhoneAuthCredential.  
  82.                 signInWithPhoneAuthCredential(credential);  
  83.             }  
  84.   
  85.             //Creating onVerificationFailed() method.  
  86.             @Override  
  87.             public void onVerificationFailed(FirebaseException e) {  
  88.                 // It is invoked when an invalid request is made for verification.                 
  89.                 //For instance, if the phone number format is not valid.  
  90.                 Log.w(TAG, "onVerificationFailed", e);  
  91.                 mVerificationInProgress = false;  
  92.   
  93.                 if (e instanceof FirebaseAuthInvalidCredentialsException) {  
  94.                     // Invalid request  
  95.                     // Setting error to text field  
  96.                     mPhoneNumberField.setError("Invalid phone number.");  
  97.                 } else if (e instanceof FirebaseTooManyRequestsException) {  
  98.                     // The SMS quota has been exceeded for the project                     
  99.                    Toast.makeText(getApplicationContext(), "Quota exceeded", Toast.LENGTH_SHORT).show();  
  100.                 }  
  101.             }  
  102.              // Creating onCodeSent() method called after the verification code has been sent by SMS to the provided phone number.     
  103.             @Override  
  104.             public void onCodeSent(String verificationId,  
  105.                                    PhoneAuthProvider.ForceResendingToken token) {  
  106.                  // The SMS verification code will be sent to the provided phone number  
  107.                 // Now need to ask the user for entering the code and then construct a credential  
  108.                 // through integrating the code with a verification ID.  
  109.                 Log.d(TAG, "onCodeSent:" + verificationId);  
  110.   
  111.                 // Save the verification ID and resend token to use them later  
  112.                 mVerificationId = verificationId;  
  113.                 mResendToken = token;  
  114.             }  
  115.         };  
  116.     }  
  117.     // Creating onStart method.  
  118.     @Override  
  119.     public void onStart() {  
  120.         super.onStart();  
  121.   
  122.         // Checking if the user is signed in or not. If signed in, then update UI accordingly.  
  123.         FirebaseUser currentUser = mAuth.getCurrentUser();  
  124.   
  125.         if (currentUser != null) {  
  126.             Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());  
  127.             Toast.makeText(MainActivity.this, "Currently Logged in: " + currentUser.getEmail(), Toast.LENGTH_LONG).show();  
  128.             mPhoneNumberViews.setVisibility(View.GONE);  
  129.             mSignedInViews.setVisibility(View.VISIBLE);  
  130.         }  
  131.         else {  
  132.             mPhoneNumberViews.setVisibility(View.VISIBLE);  
  133.             mSignedInViews.setVisibility(View.GONE);  
  134.         }  
  135.   
  136.         //check if a verification is in progress. If it is then we have to re verify.  
  137.         if (mVerificationInProgress && validatePhoneNumber()) {  
  138.             startPhoneNumberVerification(mPhoneNumberField.getText().toString());  
  139.         }  
  140.     }  
  141.     //Implementing SaveInstanceState to save the flag.  
  142.     @Override  
  143.     protected void onSaveInstanceState(Bundle outState) {  
  144.         super.onSaveInstanceState(outState);  
  145.         outState.putBoolean(KEY_VERIFY_IN_PROGRESS, mVerificationInProgress);  
  146.     }  
  147.   
  148.     //Implementing RestoreInstanceState to restore the flag.  
  149.     @Override  
  150.     protected void onRestoreInstanceState(Bundle savedInstanceState) {  
  151.         super.onRestoreInstanceState(savedInstanceState);  
  152.         mVerificationInProgress = savedInstanceState.getBoolean(KEY_VERIFY_IN_PROGRESS);  
  153.     }  
  154.   
  155.     // Creating startPhoneNumberVerification() method  
  156.    //Getting text code sent. So we can use it to sign-in.      
  157.    private void startPhoneNumberVerification(String phoneNumber) {  
  158.         PhoneAuthProvider.getInstance().verifyPhoneNumber(  
  159.                 phoneNumber,        // Phone number to verify  
  160.                 60,                 // Timeout duration  
  161.                 TimeUnit.SECONDS,   // Unit of timeout  
  162.                 this,               // Activity (for callback binding)  
  163.                 mCallbacks);        // OnVerificationStateChangedCallbacks  
  164.   
  165.         //Setting flag to say that the verification is in process.  
  166.         mVerificationInProgress = true;  
  167.     }  
  168.   
  169.      //Creating a helper method for verification of phone number with code.  
  170.     // Entering code and manually signing in with that code  
  171.     private void verifyPhoneNumberWithCode(String verificationId, String code) {  
  172.         PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);  
  173.         signInWithPhoneAuthCredential(credential);  
  174.     }  
  175.   
  176.     // Creating helper method signInWithPhoneAuthCredential().   
  177.     //Use text to sign-in.   
  178.     private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {  
  179.           
  180.          //Adding onCompleteListener to signInWithCredential.    
  181.          mAuth.signInWithCredential(credential)  
  182.                 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {  
  183.                     @Override  
  184.                     public void onComplete(@NonNull Task<AuthResult> task) {  
  185.                         if (task.isSuccessful()) {  
  186.                             //Sign-In is successful, update the UI with the signed-in user's information  
  187.                             Log.d(TAG, "signInWithCredential:success");  
  188.                             FirebaseUser user = task.getResult().getUser();  
  189.                             mPhoneNumberViews.setVisibility(View.GONE);  
  190.                             mSignedInViews.setVisibility(View.VISIBLE);  
  191.                         } else {  
  192.                            // If the SignIn fails, it will display a message and also update the UI              
  193.                             Log.w(TAG, "signInWithCredential:failure", task.getException());  
  194.                             if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {  
  195.                                 // The verification code entered was invalid  
  196.                                 mVerificationField.setError("Invalid code.");  
  197.                             }  
  198.                         }  
  199.                     }  
  200.                 });  
  201.     }  
  202.     // Creating helper method for validating phone number.   
  203.     private boolean validatePhoneNumber() {  
  204.         String phoneNumber = mPhoneNumberField.getText().toString();  
  205.         if (TextUtils.isEmpty(phoneNumber)) {  
  206.             mPhoneNumberField.setError("Invalid phone number.");  
  207.             return false;  
  208.         }  
  209.   
  210.         return true;  
  211.     }  
  212.       
  213.     //Creating helper method for resending verification code.   
  214.     private void resendVerificationCode(String phoneNumber,  
  215.                                         PhoneAuthProvider.ForceResendingToken token) {  
  216.         PhoneAuthProvider.getInstance().verifyPhoneNumber(  
  217.                 phoneNumber,        // Phone number to verify  
  218.                 60,                 // Timeout duration  
  219.                 TimeUnit.SECONDS,   // Unit of timeout  
  220.                 this,               // Activity (for callback binding)  
  221.                 mCallbacks,         // OnVerificationStateChangedCallbacks  
  222.                 token);             // ForceResendingToken from callbacks  
  223.     }  
  224.     //Adding onClick method which handles the button clicks.  
  225.     @Override  
  226.     public void onClick(View view) {  
  227.         switch (view.getId()) {  
  228.             case R.id.buttonStartVerification:  
  229.                 if (!validatePhoneNumber()) {  
  230.                     return;  
  231.                 }  
  232.                 //Calling startPhoneNumberVerification helper method for verifying phone number.  
  233.                 startPhoneNumberVerification(mPhoneNumberField.getText().toString());  
  234.                 break;  
  235.             case R.id.buttonVerifyPhone:  
  236.                 String code = mVerificationField.getText().toString();  
  237.                 if (TextUtils.isEmpty(code)) {  
  238.                     mVerificationField.setError("Cannot be empty.");  
  239.                     return;  
  240.                 }  
  241.                 //Call the verifyPhoneNumberWithCode () method.  
  242.                 verifyPhoneNumberWithCode(mVerificationId, code);  
  243.                 break;  
  244.             case R.id.buttonResend:  
  245.                 //Call the resendVerificationCode () method.  
  246.                 resendVerificationCode(mPhoneNumberField.getText().toString(), mResendToken);  
  247.                 break;  
  248.             case R.id.signOutButton:  
  249.                 //Call the signOut() method.  
  250.                 signOut();  
  251.                 break;  
  252.         }  
  253.     }  
  254.     //Create the signOut() method.   
  255.     private void signOut() {  
  256.         mAuth.signOut();  
  257.         mPhoneNumberViews.setVisibility(View.VISIBLE);  
  258.         mSignedInViews.setVisibility(View.GONE);  
  259.     }  
  260. }  

 

#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries