Get Started with Firebase Authentication on Android (2024)

Stay organized with collections Save and categorize content based on your preferences.

Connect your app to Firebase

If you haven't already,add Firebase to your Android project.

Add Firebase Authentication to your app

  1. In your module (app-level) Gradle file(usually <project>/<app-module>/build.gradle.kts or<project>/<app-module>/build.gradle),add the dependency for the Firebase Authentication library for Android. We recommend using theFirebase Android BoMto control library versioning.

    dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.3.0")) // Add the dependency for the Firebase Authentication library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-auth")}

    By using the Firebase Android BoM, your app will always use compatible versions of Firebase Android libraries.

    (Alternative) Add Firebase library dependencieswithoutusing the BoM

    If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.

    Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.

    dependencies { // Add the dependency for the Firebase Authentication library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-auth:23.0.0")}
    Looking for a Kotlin-specific library module? Starting inOctober 2023(Firebase BoM 32.5.0), both Kotlin and Java developers candepend on the main library module (for details, see theFAQ about this initiative).
  2. To use an authentication provider, you need to enable it in theFirebase console. Go to the Sign-in Method page in the Firebase Authenticationsection to enable Email/Password sign-in and any other identity providersyou want for your app.

(Optional) Prototype and test with Firebase Local Emulator Suite

Before talking about how your app authenticates users, let's introduce a set oftools you can use to prototype and test Authentication functionality:Firebase Local Emulator Suite. If you're deciding among authentication techniquesand providers, trying out different data models with public and private datausing Authentication and Firebase Security Rules, or prototyping sign-in UI designs, being able towork locally without deploying live services can be a great idea.

An Authentication emulator is part of the Local Emulator Suite, whichenables your app to interact with emulated database content and config, aswell as optionally your emulated project resources (functions, other databases,and security rules).

Using the Authentication emulator involves just a few steps:

  1. Adding a line of code to your app's test config to connect to the emulator.
  2. From the root of your local project directory, running firebase emulators:start.
  3. Using the Local Emulator Suite UI for interactive prototyping, or theAuthentication emulator REST API for non-interactive testing.

A detailed guide is available at Connect your app to the Authentication emulator.For more information, see the Local Emulator Suite introduction.

Now let's continue with how to authenticate users.

Check current auth state

  1. Declare an instance of FirebaseAuth.

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth

    Java

    private FirebaseAuth mAuth;
  2. In the onCreate() method, initialize the FirebaseAuth instance.

    Kotlin+KTX

    // Initialize Firebase Authauth = Firebase.auth

    Java

    // Initialize Firebase AuthmAuth = FirebaseAuth.getInstance();
  3. When initializing your Activity, check to see if the user is currently signedin.

    Kotlin+KTX

    public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser if (currentUser != null) { reload() }}

    Java

    @Overridepublic void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); }}

Sign up new users

Create a new createAccount method that takes in an email address and password,validates them, and then creates a new user with thecreateUserWithEmailAndPasswordmethod.

Kotlin+KTX

auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } }

Java

mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });

Add a form to register new users with their email and password and call this newmethod when it is submitted. You can see an example in ourquickstart sample.

Sign in existing users

Create a new signIn method which takes in an email address and password,validates them, and then signs a user in with thesignInWithEmailAndPassword method.

Kotlin+KTX

auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } }

Java

mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });

Add a form to sign in users with their email and password and call this newmethod when it is submitted. You can see an example in ourquickstart sample.

Access user information

If a user has signed in successfully you can get their account data atany point with the getCurrentUser method.

Kotlin+KTX

val user = Firebase.auth.currentUseruser?.let { // Name, email address, and profile photo Url val name = it.displayName val email = it.email val photoUrl = it.photoUrl // Check if user's email is verified val emailVerified = it.isEmailVerified // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. val uid = it.uid}

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();if (user != null) { // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // Check if user's email is verified boolean emailVerified = user.isEmailVerified(); // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. String uid = user.getUid();}

Next Steps

Explore the guides on adding other identity and authentication services:

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-09-16 UTC.

Get Started with Firebase Authentication on Android (2024)
Top Articles
Explore Dublin's Castles with Visit Dublin
3. Disc Structure • CLIR
Lowe's Garden Fence Roll
Oldgamesshelf
122242843 Routing Number BANK OF THE WEST CA - Wise
Affidea ExpressCare - Affidea Ireland
Blackstone Launchpad Ucf
Z-Track Injection | Definition and Patient Education
50 Meowbahh Fun Facts: Net Worth, Age, Birthday, Face Reveal, YouTube Earnings, Girlfriend, Doxxed, Discord, Fanart, TikTok, Instagram, Etc
Florida (FL) Powerball - Winning Numbers & Results
Craigslist Heavy Equipment Knoxville Tennessee
Arboristsite Forum Chainsaw
Viprow Golf
Praew Phat
Uktulut Pier Ritual Site
How pharmacies can help
Byui Calendar Fall 2023
Ukc Message Board
Wausau Marketplace
Nz Herald Obituary Notices
Regal Amc Near Me
Raw Manga 1000
Ltg Speech Copy Paste
Cylinder Head Bolt Torque Values
Where to eat: the 50 best restaurants in Freiburg im Breisgau
Insidious 5 Showtimes Near Cinemark Southland Center And Xd
Stubhub Elton John Dodger Stadium
Filmy Met
Forager How-to Get Archaeology Items - Dino Egg, Anchor, Fossil, Frozen Relic, Frozen Squid, Kapala, Lava Eel, and More!
Navigating change - the workplace of tomorrow - key takeaways
Devin Mansen Obituary
Snohomish Hairmasters
Pokemon Reborn Locations
Ferguson Employee Pipeline
Weather Underground Corvallis
Promo Code Blackout Bingo 2023
What to Do at The 2024 Charlotte International Arts Festival | Queen City Nerve
Brake Pads - The Best Front and Rear Brake Pads for Cars, Trucks & SUVs | AutoZone
Thothd Download
Sea Guini Dress Code
Maplestar Kemono
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Das schönste Comeback des Jahres: Warum die Vengaboys nie wieder gehen dürfen
Ronnie Mcnu*t Uncensored
Is My Sister Toxic Quiz
Tanger Outlets Sevierville Directory Map
Game Akin To Bingo Nyt
Powah: Automating the Energizing Orb - EnigmaticaModpacks/Enigmatica6 GitHub Wiki
Osrs Vorkath Combat Achievements
Bumgarner Funeral Home Troy Nc Obituaries
Olay Holiday Gift Rebate.com
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 6256

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.