0Pricing
Android Academy · Lesson

Firebase Authentication

Email and Google sign-in.

Firebase Authentication is a free Android Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Firebase Auth?

Firebase Authentication handles the hard parts of signing users in: secure password storage, token refresh, account recovery and many providers (email, Google, Apple, phone, anonymous).

Instead of building login servers, you call a few APIs and get a verified FirebaseUser. In this lesson you'll do email/password and Google sign-in.

Enable Sign-In Methods

Before writing code, enable the providers you want in the Firebase console:

  • Go to Authentication → Sign-in method.
  • Toggle Email/Password on.
  • Toggle Google on (pick a support email).

For Google sign-in you must also add your app's SHA-1 fingerprint in project settings, or sign-in will fail with a developer error.

Get the FirebaseAuth Instance

The entry point is Firebase.auth. It exposes the current user and methods to create accounts, sign in and sign out.

auth.currentUser is null when nobody is signed in — a quick way to decide which screen to show on launch.

import com.google.firebase.Firebase
import com.google.firebase.auth.auth

val auth = Firebase.auth

fun isLoggedIn(): Boolean {
    return auth.currentUser != null
}

Create an Account

Register a new user with createUserWithEmailAndPassword. It returns a Task, but in coroutine code you can await() it (from kotlinx-coroutines-play-services).

On success the user is immediately signed in.

import com.google.firebase.Firebase
import com.google.firebase.auth.auth
import kotlinx.coroutines.tasks.await

suspend fun register(email: String, password: String): Result<Unit> {
    return try {
        Firebase.auth
            .createUserWithEmailAndPassword(email, password)
            .await()
        Result.success(Unit)
    } catch (e: Exception) {
        Result.failure(e)
    }
}

Sign In with Email

Signing an existing user in uses signInWithEmailAndPassword. The shape mirrors registration.

Wrapping the call in try/catch lets you surface clear errors — wrong password, no such user, malformed email.

import com.google.firebase.Firebase
import com.google.firebase.auth.auth
import com.google.firebase.auth.FirebaseUser
import kotlinx.coroutines.tasks.await

suspend fun login(email: String, password: String): FirebaseUser? {
    val result = Firebase.auth
        .signInWithEmailAndPassword(email, password)
        .await()
    return result.user
}

A Login Screen in Compose

Tie auth into a small Compose screen. Hold email/password in state, call the suspend functions from a coroutine scope, and show errors.

@Composable
fun LoginScreen(onLoggedIn: () -> Unit) {
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var error by remember { mutableStateOf<String?>(null) }
    val scope = rememberCoroutineScope()

    Column(Modifier.padding(16.dp)) {
        TextField(email, { email = it }, label = { Text("Email") })
        TextField(password, { password = it }, label = { Text("Password") })
        error?.let { Text(it, color = Color.Red) }
        Button(onClick = {
            scope.launch {
                val user = login(email, password)
                if (user != null) onLoggedIn() else error = "Login failed"
            }
        }) { Text("Sign in") }
    }
}

Reading the Current User

A FirebaseUser carries identity details: uid (stable unique id), email, displayName and photoUrl.

Use uid as the key when you store that user's data in Firestore — it's guaranteed unique and unchanging.

import com.google.firebase.Firebase
import com.google.firebase.auth.auth

fun describeUser() {
    val user = Firebase.auth.currentUser ?: return
    println("UID: ${user.uid}")
    println("Email: ${user.email}")
    println("Name: ${user.displayName ?: "(none)"}")
}

Observing Auth State

Auth can change at any time (sign in, sign out, token refresh). Register an AuthStateListener to react instead of polling.

This is perfect for navigating between a login screen and a home screen automatically.

import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth

val listener = FirebaseAuth.AuthStateListener { auth ->
    val user = auth.currentUser
    if (user == null) {
        println("Signed out -> show login")
    } else {
        println("Signed in as ${user.email}")
    }
}

// Attach and detach with lifecycle
Firebase.auth.addAuthStateListener(listener)
// Firebase.auth.removeAuthStateListener(listener)

Google Sign-In with Credential Manager

The modern way to do Google sign-in is the Credential Manager API. You request a Google ID token, then exchange it for a Firebase credential.

The key step is building a GoogleAuthProvider credential from the returned ID token and passing it to signInWithCredential.

import com.google.firebase.Firebase
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.auth
import kotlinx.coroutines.tasks.await

suspend fun firebaseSignInWithGoogle(idToken: String) {
    // idToken comes from Credential Manager / Google Identity
    val credential = GoogleAuthProvider.getCredential(idToken, null)
    Firebase.auth.signInWithCredential(credential).await()
}

Signing Out

Signing out is a single call: auth.signOut(). It clears the local user and fires your auth state listener.

For Google sign-in you may also clear the Credential Manager state so the chooser appears next time. After sign-out, currentUser becomes null.

import com.google.firebase.Firebase
import com.google.firebase.auth.auth

fun logout() {
    Firebase.auth.signOut()
    // currentUser is now null; your AuthStateListener fires
}

Handling Auth Errors

Auth failures throw typed exceptions you can branch on:

  • FirebaseAuthInvalidUserException — no such user / disabled.
  • FirebaseAuthInvalidCredentialsException — wrong password or bad email.
  • FirebaseAuthUserCollisionException — email already registered.

Map these to friendly messages instead of showing raw stack traces.

import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseAuthUserCollisionException

fun messageFor(e: Throwable): String = when (e) {
    is FirebaseAuthInvalidCredentialsException -> "Wrong email or password"
    is FirebaseAuthUserCollisionException -> "That email is already in use"
    else -> "Something went wrong, try again"
}

Quick Check

You want to automatically switch the user between a login screen and a home screen whenever they sign in or out. What's the cleanest approach?

Recap: Authentication

You can now authenticate users with Firebase:

  • Enable providers in the console; add your SHA-1 for Google.
  • Use Firebase.auth with createUserWithEmailAndPassword / signInWithEmailAndPassword.
  • Google sign-in: get an ID token, build a GoogleAuthProvider credential, call signInWithCredential.
  • Read identity via currentUser (use uid as your data key).
  • React with an AuthStateListener; sign out with signOut().

Next: storing that user's data in Cloud Firestore.

Frequently asked questions

Is the “Firebase Authentication” lesson free?

Yes — the full text of “Firebase Authentication” is free to read here on the web, and the Android Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “Firebase Authentication”?

Email and Google sign-in. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Android Academy?

No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Firebase Authentication” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Android Academy lesson?

Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up Firebase
  2. Firebase Authentication
  3. Cloud Firestore Basics
  4. Push with Cloud Messaging
← Back to Android Academy