Computer scienceProgramming languagesKotlinAdditional instrumentsDatabase and StorageFirebase development

Firebase Authentication

6 minutes read

Firebase is an app development platform by Google, which provides various tools and services for developers. It helps to accelerate app development, facilitate analytics, and enhance user engagement. Firebase Authentication is one of the services provided by Firebase, allowing developers to easily and securely manage user authentication in their apps. This service supports various authentication methods, such as email and password, social media, phone, and others.

Introduction to Firebase Authentication

Firebase Authentication offers several benefits to Kotlin developers:

  1. Convenience and security: Firebase Authentication provides ready-made solutions that adhere to best security practices. This frees developers from having to implement authentication systems themselves.
  2. Cross-platform projects: Kotlin is not limited to Android development. With Kotlin Multiplatform, you can develop apps for iOS and the web as well. Firebase also supports all these platforms, making it an excellent choice for cross-platform projects in Kotlin.
  3. Integration with other Firebase services: Using Kotlin in conjunction with Firebase allows developers to easily integrate other Firebase services, such as Cloud Firestore, Realtime Database, Cloud Messaging, and more, creating a comprehensive and cohesive infrastructure for the app.
  4. Modern and efficient APIs: Kotlin is a language with modern features and convenient syntax. The Firebase SDK for Kotlin has similar qualities, enabling clean and efficient code writing.

Firebase Authentication supports various authentication methods:

  • Email and password: This method allows users to create an account using their email and password.
  • Phone: Users can sign in to the app with an SMS code sent to their mobile phone.
  • OAuth with social media providers: Firebase Authentication supports signing in through popular social networks such as Facebook, Google, Twitter, and others.
  • Anonymous authentication: This method allows users to sign in to the app anonymously, without providing personal information.
  • Custom systems and SAML: Firebase allows you to integrate your app with an existing authentication system or use SAML providers for single sign-on.
  • Token-based authentication: Developers can create their own authentication systems using JWT tokens.

Kotlin project with Firebase integration

To start a new project with Firebase Authentication, follow the steps below.

Creating a new project in IntelliJ IDEA or Android Studio

  1. Open IntelliJ IDEA or Android Studio.
  2. Select "Create New Project".
  3. Choose "Kotlin" (or "Android") as the project type and follow the project creation wizard instructions.

Setting up dependencies

  1. Open the build.gradle (Module: app) file in your project.
  2. Ensure that necessary libraries for your project are added in the "dependencies" section. Here's an example for an Android project:
implementation("androidx.core:core-ktx:1.10.1")

Creating a Project in Firebase Console

  1. Go to the Firebase Console.
  2. Click "Add project" and follow the instructions to create a new project.
  3. If necessary, set up analytics for your project by selecting the appropriate options.
  4. After the project is created, you will be prompted to add Firebase to your app (iOS/Android/Web).
  5. If you are developing an Android app:
    • In Firebase Console, after creating the project, select "Add App" and choose Android.
    • Specify your app's package name (e.g., "com.example.myapp").
    • Follow the instructions to download the google-services.json configuration file.
    • Place the google-services.json file in your Android project’s "app/" directory.

Integrating Firebase SDK into Kotlin project

For Android projects

Open the build.gradle (Project: YourProjectName) file and add the following lines to the "dependencies" section:

classpath ("com.google.gms:google-services:4.3.15")
classpath ("com.android.tools.build:gradle:7.0.4")

Open the build.gradle (Module: app) file and add the following line at the end of the file:

plugins {
    ...
    id("com.google.gms.google-services")
}

In the same build.gradle (Module: app) file, add the necessary Firebase dependencies to the "dependencies" section. For example, for Firebase Authentication and Firestore integration, add:

implementation("com.google.firebase:firebase-auth:22.1.1")
implementation("com.google.firebase:firebase-firestore:24.7.0")

Sync your project with Gradle by clicking "Sync Now" in the top panel of Android Studio.

For other types of Kotlin projects (non-Android)

Integrating Firebase into such projects may be more complex and may require the use of platform-specific libraries (e.g., Firebase Admin SDK for server applications).

These steps should help you get started with Firebase in your Kotlin project. After integrating the SDK, you can start using various Firebase services such as Authentication, Firestore, Realtime Database, Cloud Messaging, etc. Follow the Firebase documentation for up-to-date library versions and detailed instructions.

Firebase email/password authentication with Kotlin

Registering new users

To register a new user with an email and password, use the createUserWithEmailAndPassword method:


    val auth = FirebaseAuth.getInstance()
    
    auth.createUserWithEmailAndPassword("[email protected]", "password123")
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                val user = auth.currentUser
                // Registration successful
            } else {
                // If registration fails, display a message to the user
                Log.w(TAG, "createUserWithEmail:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.",
                        Toast.LENGTH_SHORT).show()
            }
        }
    

Logging in existing users

To log in an existing user with an email and password, use the signInWithEmailAndPassword method:


    val auth = FirebaseAuth.getInstance()
    
    auth.signInWithEmailAndPassword("[email protected]", "password123")
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                val user = auth.currentUser
                // Successfully logged in
            } else {
                // If login fails, display a message to the user
                Log.w(TAG, "signInWithEmail:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.",
                        Toast.LENGTH_SHORT).show()
            }
        }
    

Resetting forgotten password

If a user has forgotten their password, you can send a password reset link to their email address using the sendPasswordResetEmail method:


    val auth = FirebaseAuth.getInstance()
    
    auth.sendPasswordResetEmail("[email protected]")
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                // Password reset email sent successfully
                Log.d(TAG, "Email sent.")
            } else {
                // An error occurred, display a message to the user
                Log.w(TAG, "sendPasswordResetEmail:failure", task.exception)
                Toast.makeText(baseContext, "Failed to send reset email.",
                        Toast.LENGTH_SHORT).show()
            }
        }
    

Firebase Social Authentication

Sign In with Google

Add dependencies:

implementation("com.google.android.gms:play-services-auth:20.6.0")

Configure GoogleSignInOptions:

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(getString(R.string.default_web_client_id))
                    .requestEmail()
                    .build()

Authenticate:

val signInIntent = GoogleSignIn.getClient(this, gso).signInIntent
        val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                result: ActivityResult ->
            if (result.resultCode == Activity.RESULT_OK) {
                val intent = result.data
                // Handle the Intent
                //do stuff here
            }
        }
        fun openActivityForResult() {
            startForResult.launch(signInIntent)
        }

Sign In with Facebook

Add dependencies:

implementation("com.facebook.android:facebook-login:latest.release")

Authenticate:

val loginButton = findViewById<LoginButton>(R.id.login_button)
        loginButton.setReadPermissions("email", "public_profile")

        val callbackManager = CallbackManager.Factory.create()
        loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(loginResult: LoginResult) {
                handleFacebookAccessToken(loginResult.accessToken)
            }

            // ... other overrides
        })

Handle Result:

fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            callbackManager.onActivityResult(requestCode, resultCode, data)
        }

Sign in with Twitter and other social networks

The process for signing in with Twitter and other social networks is similar to the above. The key step is to get the appropriate tokens, create an AuthCredential object, and then call signInWithCredential.

For Twitter:

implementation("com.twitter:twitter-api-java-sdk:1.1.4")
val credential = TwitterAuthProvider.getCredential(token, secret) 
auth.signInWithCredential(credential) // ... addOnCompleteListener 

Please note that in order to work with each social network, you will need to register the application on the respective platform and obtain the necessary keys and identifiers.

Firebase Phone Authentication

Phone number verification

This step assumes that you have already configured your project in Firebase and added the firebase-auth library to your Kotlin project.

Initialization

Before using Firebase Phone Authentication, Firebase must be initialized in your app:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FirebaseApp.initializeApp(this)
        setContent {
            MyApplicationTheme {
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
                    Greeting("Android")
                }
            }
        }
    }
}

Requesting phone number

In your user interface, request the user's phone number. This is typically a standard input field where the user enters their phone number.

Sending phone number

Create a PhoneAuthOptions instance and configure it to start the verification process:

val options = PhoneAuthOptions.newBuilder(FirebaseAuth.getInstance())
            .setPhoneNumber(phoneNumber)
            .setTimeout(60L, TimeUnit.SECONDS)
            .setActivity(this)
            .setCallbacks(callbacks)
            .build()
PhoneAuthProvider.verifyPhoneNumber(options)

Receiving verification code

After the phone number is sent, the user will receive an SMS with a verification code. Provide an input field in your app for this code.

Verifying the code

When the user enters the code from the SMS, the verification must be performed:

val credential = PhoneAuthProvider.getCredential(verificationId, code)
        firebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    val user = task.result?.user
                } else {
                    // Sign in failed
                }
            }

Handling callbacks

You need to implement PhoneAuthProvider.OnVerificationStateChangedCallbacks to handle the verification states:

val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            override fun onVerificationCompleted(credential: PhoneAuthCredential) {
                firebaseAuth.signInWithCredential(credential)
            }

            override fun onVerificationFailed(e: FirebaseException) {
                // This callback is invoked in case of verification failure
            }

            override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) {
                // Save verification ID and resending token to use later
            }
        }

Notes

  • Make sure that your project in the Firebase Console has phone authentication method enabled.
  • Be mindful of security: do not pass verificationId and code between different activities directly.

Conclusion

Firebase Authentication provides ready-to-use and secure solutions, allowing you to focus on the core functionality of the application, saving you time and resources. Together with Kotlin Multiplatform, Firebase allows you to develop applications for Android, iOS, and web platforms, providing a unified and consistent experience for developers across platforms. Firebase Authentication integrates well with other Firebase services, such as Cloud Firestore and Realtime Database, creating a powerful and flexible infrastructure for your application.

4 learners liked this piece of theory. 2 didn't like it. What about you?
Report a typo