Creating Phone Authentication Using Firebase in Android Studio

You are currently viewing Creating Phone Authentication Using Firebase in Android Studio

Introduction

In the ever-evolving landscape of mobile app development, user authentication remains a critical aspect of securing your app and protecting user data. One popular method for verifying user identities is phone authentication, which allows users to log in using their phone numbers. Firebase, a powerful mobile and web application development platform by Google, offers a straightforward and secure way to implement phone authentication in your Android app. In this tutorial, we’ll walk you through the process of creating phone authentication using Firebase in Android Studio

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites in place:

  1. Android Studio: You should have Android Studio installed on your development machine.
  2. Firebase Account: You’ll need a Firebase account. You can create one by visiting the Firebase Console at https://console.firebase.google.com/.
  3. Android Emulator or Physical Device: You need an Android emulator or a physical Android device to test the authentication flow.

Setting up Firebase

Let’s start by setting up Firebase for your Android project:

Step 1: Create a Firebase Project

  1. Go to the Firebase Console.
  2. Click on “Add Project.”
  3. Enter a project name and select your country/region.
  4. Click “Continue” and follow the on-screen instructions to create your project.

Step 2: Connect Your App to Firebase

  1. In the Firebase Console, click on the project you just created.
  2. Click on the “Android” icon to add your Android app to the project.
  3. Enter your app’s package name (you can find this in your AndroidManifest.xml file).
  4. Optionally, you can enter the app’s nickname and debug signing certificate SHA-1 if needed.
  5. Click “Register App.”
  6. Download the google-services.json file and add it to your Android project’s app directory.

Step 3: Add Firebase Authentication

  1. In the Firebase Console, click on “Authentication” in the left sidebar.
  2. Click on the “Get started” button under “Sign-in method.”
  3. Enable the “Phone” sign-in provider.

Now that your Android app is connected to Firebase, let’s proceed with the implementation of phone authentication.

Implementing Phone Authentication in Android Studio

Step 4: Set Up Your Android Project

Before you can implement phone authentication, make sure your Android project is set up correctly:

  1. In your app’s build.gradle (Module: app) file, add the following dependencies:
implementation 'com.google.firebase:firebase-auth:21.0.1'

Ensure that the version number matches the latest Firebase Auth SDK version.

2.Sync your project with the Gradle files to ensure the dependencies are downloaded and added to your project.

Step 5: Design the User Interface

Create a user interface for phone authentication. You’ll typically have an EditText for the user to enter their phone number and a button to trigger the authentication process.

<!-- activity_main.xml -->
<EditText
    android:id="@+id/editTextPhoneNumber"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter your phone number"
    android:inputType="phone"/>

<Button
    android:id="@+id/buttonSendCode"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Send Verification Code"/>

Step 6: Initialize Firebase Authentication

In your app’s main activity (or any other appropriate activity), initialize Firebase Authentication in the onCreate method:

// MainActivity.java
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
    }
}

Step 7: Implement Phone Authentication

Now, let’s implement the logic for phone authentication when the user clicks the “Send Verification Code” button:

// MainActivity.java
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.auth.PhoneAuthOptions;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private EditText editTextPhoneNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...

        editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);

        // ...

        findViewById(R.id.buttonSendCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phoneNumber = editTextPhoneNumber.getText().toString().trim();

                if (phoneNumber.isEmpty()) {
                    editTextPhoneNumber.setError("Phone number is required");
                    editTextPhoneNumber.requestFocus();
                } else {
                    // Start the phone authentication process
                    PhoneAuthOptions options =
                        PhoneAuthOptions.newBuilder(mAuth)
                            .setPhoneNumber(phoneNumber)       // Phone number to verify
                            .setTimeout(60L, TimeUnit.SECONDS) // Timeout duration
                            .setActivity(MainActivity.this)    // Activity (for callback binding)
                            .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                                @Override
                                public void onVerificationCompleted(PhoneAuthCredential credential) {
                                    // Auto-retrieval or instant verification completed, log in the user.
                                    // You can automatically sign in the user by calling
                                    // mAuth.signInWithCredential(credential).
                                }

                                @Override
                                public void onVerificationFailed(FirebaseException e) {
                                    // Verification failed.
                                    // Handle error (e.g., display an error message to the user).
                                }

                                @Override
                                public void onCodeSent(@NonNull String verificationId,
                                                       @NonNull PhoneAuthProvider.ForceResendingToken token) {
                                    // The SMS verification code has been sent to the provided phone number.
                                    // Save the verification ID and the token to use later when verifying the code.
                                }
                            })
                            .build();

                    PhoneAuthProvider.verifyPhoneNumber(options);
                }
            }
        });
    }
}

Step 8: Verify the SMS Code

To complete the phone authentication process, you need to verify the SMS code sent to the user’s phone number. You can implement this in a new activity or a dialog fragment, where the user can enter the code they received.

// VerificationActivity.java
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

public class VerificationActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verification);

        mAuth = FirebaseAuth.getInstance();

        // Retrieve the verification ID and the code sent to the user's phone
        String verificationId = getIntent().getStringExtra("verificationId");
        String smsCode = "123456"; // Replace with the user's input

        // Create a PhoneAuthCredential object with the code and verification ID
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, smsCode);

        // Sign in with the credential
        mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Authentication successful, the user is signed in
                        FirebaseUser user = task.getResult().getUser();
                        // Now you can perform actions with the authenticated user
                    } else {
                        // Authentication failed
                        // Handle the failure (e.g., display an error message)
                    }
                }
            });
    }
}

Step 9: Add the Verification Activity to AndroidManifest.xml

Don’t forget to add the VerificationActivity to your AndroidManifest.xml file:

<!-- AndroidManifest.xml -->
<activity android:name=".VerificationActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Step 10: Test Your Phone Authentication Flow

Now that you’ve implemented phone authentication, it’s time to test your app. Run your app on an Android emulator or a physical device, enter a valid phone number, and observe the authentication flow.

Conclusion

In this tutorial, we’ve covered the process of creating phone authentication using Firebase in Android Studio. Phone authentication is a convenient and secure way to allow users to access your app without the need for traditional email and password-based authentication. By following the steps outlined in this tutorial, you can enhance the security and user experience of your Android app while simplifying the login process for your users. Firebase’s integration with Android Studio makes implementing phone authentication a straightforward task, allowing you to focus on building the core features of your app. Happy coding!

YOU MAY ALSO LIKE:

Implementing Facebook Authentication with Firebase in Android Studio

Implementing Google Authentication in Android Studio with Firebase

Leave a Reply