Intro to Android Development
  • Welcome
  • Syllabus
  • Hack Challenge
  • Resources
    • Lecture Videos
    • Ed Discussion
    • Git & GitHub Help/How-To
    • Setting up Android Studio
    • Starting an Android Studio Project & Making an Emulator
    • Importing, Exporting, & Submitting Your Projects to CMS
  • SP25 Course Material
    • Week 1 | Course Logistics, Kotlin, & Basic UI
      • Relevant Links
      • Demo/Lecture: Eatery Card
      • A0: Eatery Card (Follow-Along)
    • Week 2 | States, Components, LazyColumn
      • Relevant Links
      • Demo: Todo List
      • A2: Shopping List
    • Week 3 | Navigation & Animations
      • Relevant Links
      • Demo: Onboarding
      • A3: Stock Trading (RobbingGood)
    • Week 4 | MVVM and Flows
      • Relevant Links
      • Demo: Eatery Card 2
      • A4: Chat of a Lifetime
    • Week 5 | Dumb Components & UIEvents
      • Relevant Links
      • Demo: Music Player
      • A5: Rate My Vibe
    • Week 6 | Coroutines, Networking, JSON
      • Relevant Links
      • Demo: Retrofit
      • A6: You Should Even Lift, Bro.
  • Bonus Week | Android Job Search
    • Relevant Links
    • Android Technical Interview Question!
  • Textbook
    • 1. Introduction to the Editor and Views
      • 1.1 Introduction to the Editor
      • 1.2 SDK Management
      • 1.3 Kotlin Overview
      • 1.4 Views
      • 1.5 Android Studio Project Demo + Understanding The Editor
    • 2. Jetpack Compose
      • 2.1 Introduction
      • 2.2 Layouts
      • 2.3 Modifiers
      • 2.4 Animations
      • 2.5 Lazy Lists
      • 2.6 Reactive UI
    • 3. Intents and Manifest
      • 3.1 Activities
      • 3.2 Implicit Intents
      • 3.3 Explicit Intents
      • 3.4 Manifest
      • 3.5 Permissions
      • 3.6 Summary
    • 4. Navigation
      • 4.1 Types of Navigation
      • 4.2 Implementation of the Bottom Navigation Bar
    • 5. Data and Persistent Storage
      • 5.1 Singleton Classes
      • 5.2 Shared Preferences
      • 5.3 Rooms
      • 5.4 Entities
      • 5.5 Data Access Objects
      • 5.6 Databases
    • 5.5 Concurrency
      • 5.5.1 Coroutines
      • 5.5.2 Implementation of Coroutines
      • 5.5.3 Coroutines with Networking Calls
    • 6. Networking and 3rd Party libraries
      • 6.1 HTTP Overview
      • 6.2 3rd Party Libraries
      • 6.3 JSON and Moshi
      • 6.4 Retrofit
      • 6.5 Summary
    • 7. MVVM Design Pattern
      • 7.1 Key Idea
      • 7.2 Implementation Ideas
    • 8. Flows
    • 9. The Art and Ontology of Software
    • 10. 🔥 Firebase
      • 10.1 Setting up Firebase
      • 10.2 Authentication
      • 10.3 Analytics
      • 10.4 Messaging
      • 10.5 Firestore
  • Additional Topics
    • Git and GitHub
    • Exporting to APK
  • Archive
    • Archived Native Android Textbook Pages
      • 1. Layouts and More Views
        • 1.1 File Structure and File Types
        • 1.2 Resource Files
        • 1.3 Button and Input Control
        • 1.4 ViewGroups
        • 1.5 Summary + A Note On Chapter 2 Topics
      • 2. RecyclerViews
        • 2.1 RecyclerViews
        • 2.2 RecyclerView Performance
        • 2.3 Implementation of a Recycler View
        • 2.4 Implementation with Input Controls
        • 2.5 Filtering RecyclerViews
        • 2.6 Recyclerview Demo
      • 3. ListViews and Searching
        • 3.1 ListView vs. RecyclerView
        • 3.2 ListView Performance
        • 3.3 Implementation of a ListView
        • 3.4 Searching in a List View
      • 4. Fragments
        • 4.1 What are Fragments?
        • 4.2 Lifecycle of a Fragment
        • 4.3 Integrating a Fragment into an Activity
        • 4.4 Sharing Data Between Fragments
        • 4.5 Fragment Slide Shows
      • 5. OkHttp
      • 6. Activity Lifecycle
      • 7. Implementation of Tab Layout
    • Fall 2024 Course Material
      • Lecture 1 & Exercise 1: Introduction to Android
      • Lecture 1.5: Beauty of Kotlin
      • Lecture 2 & HW 2: Modifiers, Lazylists and Reactive UI
      • Lecture 3 & HW 3: Animations, Intents and Manifest
      • Lecture 4 & HW 4: Coroutines & Navigation
      • Lecture 5 & HW 5: Persistent Storage, Networking, and JSON Parsing
      • Lecture 6 & HW 6: MVVM, Flows
      • Bonus Lectures & Bonus HW
      • Bonus Lecture: Industry Practice
    • Spring 2024 Course Material
      • Lecture 1 & Exercise 1: Introduction to Android
      • Lecture 4 & HW 4: LazyLists
      • Lecture 6 & HW 6: Networking, Data, and Persistent Storage
    • Spring 2020 Course Material
      • Week 1: Intro to the Editor
      • Week 2: Views and Layouts
      • Week 3: Intent and Manifest
      • Week 4: ListView and RecyclerView
      • Week 5: Fragments
      • Week 6: Networking
    • Spring 2021 Lecture & HW 8: Networking & 3rd Party APIs
    • HackOurCampus Workshop
Powered by GitBook
On this page
  • Setting up Authentication
  • General
  • Check for signed-in users
  • Sign-out
  • Google Sign-In
  • Password Authentication

Was this helpful?

  1. Textbook
  2. 10. 🔥 Firebase

10.2 Authentication

Previous10.1 Setting up FirebaseNext10.3 Analytics

Last updated 7 months ago

Was this helpful?

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more

Setting up Authentication

Make sure your Firebase project is set up, the steps of which are covered in the first section 11.1!

Add these two dependencies to your module-level Gradle file:

implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.android.gms:play-services-auth:19.0.0'

These dependencies add the Firebase Authentication Android library and Google Play services SDK to your app.

When accessing most Authentication services, you need the appropriate FirebaseAuth object.

First, declare your auth variable:

private lateinit var auth: FirebaseAuth

In the onCreate/onCreateView method of your activity/fragment, initialize the auth variable as so:

auth = Firebase.auth

General

Check for signed-in users

When initializing your Activity, check to see if the user is currently signed in in your onStart method (which is called automatically after onCreate):

override fun onStart() {
    super.onStart()
    val currentUser = auth.currentUser
    if (currentUser == null) {
        /**
         * No user is currently signed in, can update UI elements to account for this
         * or maybe redirect to some sign in activity!
         */
    } else {
        /**
         * A signed in user is detected, carry out some respective actions if needed!
         */
    }
}

Sign-out

You can sign out a user using:

Firebase.auth.signOut()

Google Sign-In

This will most likely just be a collection of the links below, some personal reflections also!

private lateinit var googleSignInClient: GoogleSignInClient

......

// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build()

googleSignInClient = GoogleSignIn.getClient(this, gso)

3. Add an ActivityResultLauncher for the Google Sign In Activity intent (the API launches a separate activity to sign the user in):

    private lateinit var intentLauncher: ActivityResultLauncher<Intent>
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        intentLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                ...
            }
        ...
    }

4. You can add a handy Google sign-in button via:

<com.google.android.gms.common.SignInButton
 android:id="@+id/sign_in_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 
 <!--  Can add app:buttonSize attribute and specifiy icon_only, standard, or wide-->
 <!--  Can add app:colorScheme attribute and specifiy dark, light, or auto-->

5. You can then register the OnClickListener for this button in your activity via:

findViewById<SignInButton>(R.id.sign_in_button).setOnClickListener(this)
override fun onClick(view: View?) {
    if (view != null) {
        when (view.id) {
            R.id.sign_in_button -> {
                signInGoogle();
            }
        // ...
        }
    }
}
private fun signInGoogle() {
    val signInIntent = googleSignInClient.signInIntent
    intentLauncher.launch(signInIntent)
}

7. Expand the intent launcher

private lateinit var intentLauncher: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
    ...
    intentLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
                try {
                    // Google Sign In was successful, authenticate with Firebase
                    val account = task.getResult(ApiException::class.java)!!
                    firebaseAuthWithGoogle(account.idToken!!)
                } catch (e: ApiException) {
                    // Google Sign In failed, update UI appropriately
                }
            }
        }
    ...
}

8. After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential:

    private fun firebaseAuthWithGoogle(idToken: String) {
        val credential = GoogleAuthProvider.getCredential(idToken, null)
        auth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    /**
                     * A signed in user is detected, carry out some respective actions if needed!
                     */
                    val user = auth.currentUser
                    ...
                } else {
                    /**
                     * No user is currently signed in, can update UI elements to account for this
                     * and display some feedback to the user.
                     */
                }
            }
    }

9. All done :)

Password Authentication

2. When a new user signs up using your app's sign-up form, complete any new account validation steps that your app requires, such as verifying that the new account's password was correctly typed and meets your complexity requirements.

EditTexts are very useful for fields for input for emails/passwords!

3. Create a new account by passing the new user's email address and password to createUserWithEmailAndPassword:

auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                /**
                 * A signed in user is detected, carry out some respective actions if needed!
                 */
                val user = auth.currentUser
            } else {
                /**
                 * No user is currently signed in, can update UI elements to account for this
                 * and display some feedback to the user.
                 */
            }
        }

Creating an account automatically signs a user in!

If given some email and password, you can sign in a user with signInWithEmailAndPassword:

auth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                /**
                 * A signed in user is detected, carry out some respective actions if needed!
                 */
                val user = auth.currentUser
                ...
             } else {
                /**
                 * No user is currently signed in, can update UI elements to account for this
                 * and display some feedback to the user.
                 */
            }
        }

Check out to see operations one can do on a user object!

1. Enable Google Sign-In in the Firebase console: 1.1. In the , open the Auth section for your project 1.2. On the Sign in method tab, enable the Google sign-in method and click Save.

2. In your sign-in activity's onCreate method, configure Google Sign-In to request the user data required by your app. For example, to configure Google Sign-In to request users' ID and basic profile information, create a object with the DEFAULT_SIGN_IN parameter. To request users' email addresses as well, create the GoogleSignInOptions object with the requestEmail option.

If you need to request additional scopes to access Google APIs, specify them with . For the best user experience, on sign-in, only request the scopes that are required for your app to minimally function. Request any additional scopes only when you need them, so that your users see the consent screen in the context of an action they performed. See .

6. In the activity's onClick method, handle sign-in button taps by creating a sign-in intent with the method, and starting the intent with the ActivityResultLauncher.

Many of the other providers (i.e. Facebook and Twitter and GitHub) follow similar patterns. If you find yourself using multiple of these in your app in your authentication process, it may be worth it looking into for seamless integration.

.1. Enable Email/Password sign-in: 1.1. In the , open the Auth section. 1.2. On the Sign in method tab, enable the Email/password sign-in method and click Save.

If you are looking for a good password strength detector, take a look at , which is used by Dropbox.

Firebase Auth offers many more ways to authenticate users, I implore you to explore the and see what could possibly fit your needs!

https://firebase.google.com/docs/auth
Manage Users
Firebase console
GoogleSignInOptions
requestScopes
Requesting Additional Scopes
getSignInIntent
FirebaseUI
Firebase console
zxcvbn
API
Authenticate Using Google Sign-In on Android  |  Firebase DocumentationFirebase
Integrating Google Sign-In into Your Android App  |  Google Sign-In for Android  |  Google DevelopersGoogle Developers
Authentication section in the console
Authentication section in the console
Logo
Logo