Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Android Jetpack Compose - Phone Authentication using Firebase
Next article icon

Android Jetpack Compose - Phone Authentication using Firebase

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Many apps require their users to be authenticated. So for the purpose of authenticating the apps uses phone number authentication inside their apps. In phone, authentication user has to verify his identity with his phone number. Inside the app user has to enter his phone number after that he will receive a verification code on his mobile number. He has to enter that verification code and verify his identity. So this is how phone authentication works. Firebase provides so many ways for authentication users such as Google, Email and Password, Phone, and many more. In this article, we will take a look at the implementation of Phone Authentication inside our App using Firebase in Android using Jetpack Compose.

What we are going to build in this article?

We will be creating a simple application which is having two screens. The first screen will be our Verification screen on which the user has to add his phone number. After adding his phone number, the user will click on the Get OTP button after that Firebase will send OTP to that number which is mentioned above. After receiving that OTP user has to enter that OTP in the below text field and click on the below button to verify with entered OTP. After clicking on verify button Firebase will verify the OTP and allow the user to enter into the home screen only when entered OTP is correct else the user will get an error message. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it.

Kotlin
package com.example.newcanaryproject.ui.theme  import androidx.compose.ui.graphics.Color  val Purple200 = Color(0xFF0F9D58) val Purple500 = Color(0xFF0F9D58) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)  // on below line we are adding different colors. val greenColor = Color(0xFF0F9D58) 

Step 3: Connect your app to Firebase

After creating a new project, navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.  

 

After clicking on email and password authentication you will get to see the below screen. Inside this screen click on the first option to connect to firebase and after that click on the second option to Add Firebase authentication to your app.  

 

Step 4: Verify that dependency for Firebase authentication is added inside your app

After connecting your app to Firebase. Make sure to add this dependency in your build.gradle file if not added. After adding this dependency sync your project.  

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

Note: Make sure to add the exact dependency version in the above image because the latest dependency is not having the implementation for auto-detection of OTP.

Step 5: Adding internet permissions

Add internet permissions in AndroidManifest.xml. 

XML
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Step 6: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin
package com.example.firebaseproject  import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.os.Bundle import android.text.TextUtils import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.firebaseproject.ui.theme.FirebaseProjectTheme import com.example.firebaseproject.ui.theme.greenColor import com.google.firebase.FirebaseException import com.google.firebase.auth.* import com.google.firebase.auth.PhoneAuthProvider.ForceResendingToken import com.google.firebase.auth.PhoneAuthProvider.OnVerificationStateChangedCallbacks import java.util.concurrent.TimeUnit  class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContent {             FirebaseProjectTheme {                 // A surface container using the                 // 'background' color from the theme                 Surface(                     // on below line we are specifying modifier and color for our app                     modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background                 ) {                     // on the below line we are specifying the theme as the scaffold.                     Scaffold(                         // in scaffold we are specifying the top bar.                         topBar = {                             // inside top bar we are specifying background color.                             TopAppBar(backgroundColor = greenColor,                                 // along with that we are specifying                                  // title for our top bar.                                 title = {                                     // in the top bar we are specifying tile as a text                                     Text(                                         // on below line we are specifying                                          // text to display in top app bar                                         text = "GFG",                                         // on below line we are specifying                                          // modifier to fill max width                                         modifier = Modifier.fillMaxWidth(),                                         // on below line we are specifying                                         // text alignment                                         textAlign = TextAlign.Center,                                         // on below line we are specifying                                         // color for our text.                                         color = Color.White                                     )                                 })                         }) {                         // on below line we are calling                          // method to display UI                         firebaseUI(LocalContext.current)                     }                 }             }         }     } }  @Composable fun firebaseUI(context: Context) {      // on below line creating variable for course name,     // course duration and course description.     val phoneNumber = remember {         mutableStateOf("")     }      val otp = remember {         mutableStateOf("")     }      val verificationID = remember {         mutableStateOf("")     }      val message = remember {         mutableStateOf("")     }      // on below line creating variable      // for firebase auth and callback     var mAuth: FirebaseAuth = FirebaseAuth.getInstance();     lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks        // on below line creating a column     // to display our retrieved image view.     Column(         // adding modifier for our column         modifier = Modifier             .fillMaxHeight()             .fillMaxWidth()             .background(Color.White),         // on below line adding vertical and         // horizontal alignment for column.         verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally     ) {         // on below line creating text field for phone number.         TextField(             // on below line we are specifying             // value for our course name text field.             value = phoneNumber.value,             // on below line specifying key board type as number.             keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),              // on below line we are adding on             // value change for text field.             onValueChange = { phoneNumber.value = it },              // on below line we are adding place holder             // as text as "Enter your course name"             placeholder = { Text(text = "Enter your phone number") },              // on below line we are adding modifier to it             // and adding padding to it and filling max width             modifier = Modifier                 .padding(16.dp)                 .fillMaxWidth(),              // on below line we are adding text style             // specifying color and font size to it.             textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),              // on below line we are adding             // single line to it.             singleLine = true,         )          // on below line adding spacer.         Spacer(modifier = Modifier.height(10.dp))          // on below line creating button to send verification code.         Button(             onClick = {                 // on below line we are validating user inputs                 if (TextUtils.isEmpty(phoneNumber.value.toString())) {                     Toast.makeText(context, "Please enter phone number..", Toast.LENGTH_SHORT)                         .show()                 } else {                      val number = "+91${phoneNumber.value}"                     // on below line calling method to generate verification code.                     sendVerificationCode(number, mAuth, context as Activity, callbacks)                 }             },             // on below line we are             // adding modifier to our button.             modifier = Modifier                 .fillMaxWidth()                 .padding(16.dp)         ) {             // on below line we are adding text for our button             Text(text = "Generate OTP", modifier = Modifier.padding(8.dp))         }          // adding spacer on below line.         Spacer(modifier = Modifier.height(10.dp))          // on below line creating text field for otp         TextField(             // on below line we are specifying             // value for our course duration text field.             value = otp.value,             //specifying key board on below line.             keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),             // on below line we are adding on             // value change for text field.             onValueChange = { otp.value = it },              // on below line we are adding place holder             // as text as "Enter your course duration"             placeholder = { Text(text = "Enter your otp") },              // on below line we are adding modifier to it             // and adding padding to it and filling max width             modifier = Modifier                 .padding(16.dp)                 .fillMaxWidth(),              // on below line we are adding text style             // specifying color and font size to it.             textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),              // on below line we are adding             // single line to it.             singleLine = true,         )          // adding spacer on below line.         Spacer(modifier = Modifier.height(10.dp))          // on below line creating button to add          // data to firebase firestore database.         Button(             onClick = {                 // on below line we are validating                  // user input parameters.                 if (TextUtils.isEmpty(otp.value.toString())) {                     // displaying toast message on below line.                     Toast.makeText(context, "Please enter otp..", Toast.LENGTH_SHORT)                         .show()                 } else {                     // on below line generating phone credentials.                     val credential: PhoneAuthCredential = PhoneAuthProvider.getCredential(                         verificationID.value, otp.value                     )                     // on below line signing within credentials.                     signInWithPhoneAuthCredential(                         credential,                         mAuth,                         context as Activity,                         context,                         message                     )                 }             },             // on below line we are             // adding modifier to our button.             modifier = Modifier                 .fillMaxWidth()                 .padding(16.dp)         ) {             // on below line we are adding text for our button             Text(text = "Verify OTP", modifier = Modifier.padding(8.dp))         }          // on below line adding spacer.         Spacer(modifier = Modifier.height(5.dp))          Text(             // on below line displaying message for verification status.             text = message.value,             style = TextStyle(color = greenColor, fontSize = 20.sp, fontWeight = FontWeight.Bold)         )     }      // on below line creating callback     callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {         override fun onVerificationCompleted(p0: PhoneAuthCredential) {             // on below line updating message              // and displaying toast message             message.value = "Verification successful"             Toast.makeText(context, "Verification successful..", Toast.LENGTH_SHORT).show()         }          override fun onVerificationFailed(p0: FirebaseException) {             // on below line displaying error as toast message.             message.value = "Fail to verify user : \n" + p0.message             Toast.makeText(context, "Verification failed..", Toast.LENGTH_SHORT).show()         }          override fun onCodeSent(verificationId: String, p1: ForceResendingToken) {             // this method is called when code is send             super.onCodeSent(verificationId, p1)             verificationID.value = verificationId         }     } }  // on below line creating method to  // sign in with phone credentuals. private fun signInWithPhoneAuthCredential(     credential: PhoneAuthCredential,     auth: FirebaseAuth,     activity: Activity,     context: Context,     message: MutableState<String> ) {     // on below line signing with credentials.     auth.signInWithCredential(credential)         .addOnCompleteListener(activity) { task ->             // displaying toast message when              // verification is successful             if (task.isSuccessful) {                 message.value = "Verification successful"                 Toast.makeText(context, "Verification successful..", Toast.LENGTH_SHORT).show()             } else {                 // Sign in failed, display a message                 if (task.exception is FirebaseAuthInvalidCredentialsException) {                     // The verification code                      // entered was invalid                     Toast.makeText(                         context,                         "Verification failed.." + (task.exception as FirebaseAuthInvalidCredentialsException).message,                         Toast.LENGTH_SHORT                     ).show()                 }             }         } }  // below method is use to send // verification code to user phone number. private fun sendVerificationCode(     number: String,     auth: FirebaseAuth,     activity: Activity,     callbacks: OnVerificationStateChangedCallbacks ) {     // on below line generating options for verification code     val options = PhoneAuthOptions.newBuilder(auth)         .setPhoneNumber(number) // Phone number to verify         .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit         .setActivity(activity) // Activity (for callback binding)         .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks         .build()     PhoneAuthProvider.verifyPhoneNumber(options) } 

Step 7: Now we have to enable Firebase Phone Authentication in our Firebase Console 

For enabling Phone authentication in the Firebase console. Go to the Firebase Console. Now click on the Go to Console option and navigate to your project. After that click on your project. You can get to see the below screen. 

 

After clicking on Authentication you will get to see the below screen. On this screen click on the Sign-in method tab.

 

After clicking on Sign in-method you will get to see the below list of authentication screens. Click on the Phone option and enable it.

 

Click on the Phone option and you will get to see the below pop-up screen. Inside this screen click on enable the option and save it.

 

After this Run your app on a real device and see the output of the app.

Note: For getting OTP don't enter your phone number with your country code because we are already adding that country code to our code itself.

Output:


Next Article
Android Jetpack Compose - Phone Authentication using Firebase

C

chaitanyamunje
Improve
Article Tags :
  • Technical Scripter
  • Kotlin
  • Android
  • Technical Scripter 2022
  • Android-Jetpack

Similar Reads

    User authentication using Firebase in Android
    Firebase is a platform that helps developers build mobile and web apps. It provides useful tools like databases, cloud storage, and hosting. One of its main features is email and password login, so developers don’t have to create their own system for user authentication. This makes app development e
    7 min read
    Firebase Authentication with Phone Number OTP in Android
    Many apps require their users to be authenticated. So for the purpose of authenticating the apps uses phone number authentication inside their apps. In phone authentication, the user has to verify his identity with his phone number. Inside the app user has to enter his phone number after that he wil
    8 min read
    Google Signing using Firebase Authentication in Android
    Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. Google Sign-In is a secure way to
    8 min read
    How to Setup Firebase Email Authentication in Android with Example
    Service-access permissions are configured using a mechanism called Firebase authentication. This is accomplished by using Google's Firebase APIs and Firebase console to create and manage legitimate user accounts. You'll discover how to integrate Firebase authentication into an Android application in
    4 min read
    How to Remove Firebase Authentication in Android Studio?
    Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as: A blended environment where one can
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences