Authenticate with Firebase Using Email Link in Android  |  Firebase Authentication (2024)

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

You can use Firebase Authentication to sign in a user by sending them an emailcontaining a link, which they can click to sign in. In the process, the user'semail address is also verified.

There are numerous benefits to signing in by email:

  • Low friction sign-up and sign-in.
  • Lower risk of password reuse across applications, which can undermine securityof even well-selected passwords.
  • The ability to authenticate a user while also verifying that the user is thelegitimate owner of an email address.
  • A user only needs an accessible email account to sign in. No ownership of aphone number or social media account is required.
  • A user can sign in securely without the need to provide (or remember) apassword, which can be cumbersome on a mobile device.
  • An existing user who previously signed in with an email identifier (passwordor federated) can be upgraded to sign in with just the email. For example, auser who has forgotten their password can still sign in without needing toreset their password.

Before you begin

Set up your Android project

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

  2. 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.

    Also, as part of setting up Firebase Authentication, you need to add theGoogle Play services SDK to your app.

    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")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }

    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")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.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).

Enable Email Link sign-in for your Firebase project

To sign in users by email link, you must first enable the Email provider andEmail link sign-in method for your Firebase project:

  1. In the Firebase console, open the Auth section.
  2. On the Sign in method tab, enable the Email/Password provider. Notethat email/password sign-in must be enabled to use email link sign-in.
  3. In the same section, enable Email link (passwordless sign-in) sign-inmethod.
  4. Click Save.

Send an authentication link to the user's email address

To initiate the authentication flow, present the user with an interface thatprompts the user to provide their email address and then callsendSignInLinkToEmail to request that Firebase send the authentication link tothe user's email.

  1. Construct the ActionCodeSettingsobject, which provides Firebase with instructions on how to construct theemail link. Set the following fields:

    • url: The deep link to embed and any additional state to be passed along.The link's domain has to be whitelisted in the Firebase Console list ofauthorized domains, which can be found by going to the Sign-in method tab(Authentication -> Sign-in method). The link will redirect the user tothis URL if the app is not installed on their device and the app was notable to be installed.
    • androidPackageName and IOSBundleId: The apps to use when the sign-inlink is opened on an Android or Apple device. Learn more on how toconfigure Firebase Dynamic Linksto open email action links via mobile apps.
    • handleCodeInApp: Set to true. The sign-in operation has to always becompleted in the app unlike other out of band email actions (passwordreset and email verifications). This is because, at the end of the flow,the user is expected to be signed in and their Auth state persisted withinthe app.
    • dynamicLinkDomain: When multiple custom dynamic link domains are definedfor a project, specify which one to use when the link is to be opened viaa specified mobile app (for example, example.page.link). Otherwise thefirst domain is automatically selected.

    Kotlin+KTX

    val actionCodeSettings = actionCodeSettings { // URL you want to redirect back to. The domain (www.example.com) for this // URL must be whitelisted in the Firebase Console. url = "https://www.example.com/finishSignUp?cartId=1234" // This must be true handleCodeInApp = true setIOSBundleId("com.example.ios") setAndroidPackageName( "com.example.android", true, // installIfNotAvailable "12", // minimumVersion )}

    Java

    ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder() // URL you want to redirect back to. The domain (www.example.com) for this // URL must be whitelisted in the Firebase Console. .setUrl("https://www.example.com/finishSignUp?cartId=1234") // This must be true .setHandleCodeInApp(true) .setIOSBundleId("com.example.ios") .setAndroidPackageName( "com.example.android", true, /* installIfNotAvailable */ "12" /* minimumVersion */) .build();

    To learn more on ActionCodeSettings, refer to thePassing State in Email Actionssection.

  2. Ask the user for their email.

  3. Send the authentication link to the user's email, and save the user's emailin case the user completes the email sign-in on the same device.

    Kotlin+KTX

    Firebase.auth.sendSignInLinkToEmail(email, actionCodeSettings) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Email sent.") } }

    Java

    FirebaseAuth auth = FirebaseAuth.getInstance();auth.sendSignInLinkToEmail(email, actionCodeSettings) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); } } });

Complete sign in with the email link

Security concerns

To prevent a sign-in link from being used to sign in as an unintended user or onan unintended device, Firebase Auth requires the user's email address to beprovided when completing the sign-in flow. For sign-in to succeed, this emailaddress must match the address to which the sign-in link was originally sent.

You can streamline this flow for users who open the sign-in link on the samedevice they request the link, by storing their email address locally - forinstance using SharedPreferences - when you send the sign-in email. Then,use this address to complete the flow.Do not pass the user’s email in the redirect URL parameters and re-use it asthis may enable session injections.

After sign-in completion, any previous unverified mechanism of sign-in will beremoved from the user and any existing sessions will be invalidated.For example, if someone previously created an unverified account with the sameemail and password, the user’s password will be removed to prevent theimpersonator who claimed ownership and created that unverified account fromsigning in again with the unverified email and password.

Also make sure you use an HTTPS URL in production to avoid your link beingpotentially intercepted by intermediary servers.

Completing sign-in in an Android App

Firebase Authentication uses Firebase Dynamic Links to send the email link to amobile device. For sign-in completion via mobile application, the applicationhas to be configured to detect the incoming application link, parse theunderlying deep link and then complete the sign-in.

Configuring Firebase Dynamic Links

Firebase Auth uses Firebase Dynamic Links when sending alink that is meant to be opened in a mobile application. In order to use thisfeature, Dynamic Links must be configured in the Firebase Console.

  1. Enable Firebase Dynamic Links:

    1. In the Firebase console, open the Dynamic Links section.
    2. If you have not yet accepted the Dynamic Links terms and created a Dynamic Links domain, do so now.

      If you already created a Dynamic Links domain, take note of it. A Dynamic Links domain typically looks like the following example:

      example.page.link

      You will need this value when you configure your Apple or Android app to intercept the incoming link.

  2. Configuring Android applications:

    1. In order to handle these links from your Android application, theAndroid package name needs to be specified in the Firebase Consoleproject settings. In addition, the SHA-1 and SHA-256 of the applicationcertificate need to be provided.
    2. Now that you have added a dynamic link domain and ensured that yourAndroid app is configured correctly, the dynamic link will redirect toyour application, starting from the launcher activity.
    3. If you want the dynamic link to redirect to a specific activity, youwill need to configure an intent filter in your AndroidManifest.xmlfile. This can be done by either specifying your dynamic link domain orthe email action handler in the intent filter. By default, the emailaction handler is hosted on a domain like the following example:
      PROJECT_ID.firebaseapp.com/
    4. Caveats:
      1. Do not specify the URL you set on the actionCodeSettings in yourintent filter.
      2. When creating your dynamic link domain you may have also created ashort URL link. This short URL will not be passed; do notconfigure your intent filter to catch it with anandroid:pathPrefix attribute. This means that you willnot be able to catch different dynamic links in different parts ofyour application. However, you can check the mode query parameterin the link to see what operation is attempting to be performed, oruse SDK methods such as isSignInWithEmailLink to see ifa link that your app has received does what you want.
    5. For more on receiving dynamic links, refer toReceiving Android Dynamic Links instructions.

Verify link and sign in

After you receive the link as described above, verify that it is meant for emaillink authentication and complete the sign in.

Kotlin+KTX

val auth = Firebase.authval intent = intentval emailLink = intent.data.toString()// Confirm the link is a sign-in with email link.if (auth.isSignInWithEmailLink(emailLink)) { // Retrieve this from wherever you stored it val email = "someemail@domain.com" // The client SDK will parse the code from the link for you. auth.signInWithEmailLink(email, emailLink) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Successfully signed in with email link!") val result = task.result // You can access the new user via result.getUser() // Additional user info profile *not* available via: // result.getAdditionalUserInfo().getProfile() == null // You can check if the user is new or existing: // result.getAdditionalUserInfo().isNewUser() } else { Log.e(TAG, "Error signing in with email link", task.exception) } }}

Java

FirebaseAuth auth = FirebaseAuth.getInstance();Intent intent = getIntent();String emailLink = intent.getData().toString();// Confirm the link is a sign-in with email link.if (auth.isSignInWithEmailLink(emailLink)) { // Retrieve this from wherever you stored it String email = "someemail@domain.com"; // The client SDK will parse the code from the link for you. auth.signInWithEmailLink(email, emailLink) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "Successfully signed in with email link!"); AuthResult result = task.getResult(); // You can access the new user via result.getUser() // Additional user info profile *not* available via: // result.getAdditionalUserInfo().getProfile() == null // You can check if the user is new or existing: // result.getAdditionalUserInfo().isNewUser() } else { Log.e(TAG, "Error signing in with email link", task.getException()); } } });}

To learn more on how to handle sign-in with email link in an Appleapplication, refer to the Apple platforms guide.

To learn about how to handle sign-in with email link in a webapplication, refer to the Web guide.

Linking/re-authentication with email link

You can also link this method of authentication to an existing user. For examplea user previously authenticated with another provider, such as a phone number,can add this method of sign-in to their existing account.

The difference would be in the second half of the operation:

Kotlin+KTX

// Construct the email link credential from the current URL.val credential = EmailAuthProvider.getCredentialWithLink(email, emailLink)// Link the credential to the current user.Firebase.auth.currentUser!!.linkWithCredential(credential) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Successfully linked emailLink credential!") val result = task.result // You can access the new user via result.getUser() // Additional user info profile *not* available via: // result.getAdditionalUserInfo().getProfile() == null // You can check if the user is new or existing: // result.getAdditionalUserInfo().isNewUser() } else { Log.e(TAG, "Error linking emailLink credential", task.exception) } }

Java

// Construct the email link credential from the current URL.AuthCredential credential = EmailAuthProvider.getCredentialWithLink(email, emailLink);// Link the credential to the current user.auth.getCurrentUser().linkWithCredential(credential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "Successfully linked emailLink credential!"); AuthResult result = task.getResult(); // You can access the new user via result.getUser() // Additional user info profile *not* available via: // result.getAdditionalUserInfo().getProfile() == null // You can check if the user is new or existing: // result.getAdditionalUserInfo().isNewUser() } else { Log.e(TAG, "Error linking emailLink credential", task.getException()); } } });

This can also be used to re-authenticate an email link user before running asensitive operation.

Kotlin+KTX

// Construct the email link credential from the current URL.val credential = EmailAuthProvider.getCredentialWithLink(email, emailLink)// Re-authenticate the user with this credential.Firebase.auth.currentUser!!.reauthenticateAndRetrieveData(credential) .addOnCompleteListener { task -> if (task.isSuccessful) { // User is now successfully reauthenticated } else { Log.e(TAG, "Error reauthenticating", task.exception) } }

Java

// Construct the email link credential from the current URL.AuthCredential credential = EmailAuthProvider.getCredentialWithLink(email, emailLink);// Re-authenticate the user with this credential.auth.getCurrentUser().reauthenticateAndRetrieveData(credential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // User is now successfully reauthenticated } else { Log.e(TAG, "Error reauthenticating", task.getException()); } } });

However, as the flow could end up on a different device where the original userwas not logged in, this flow might not be completed. In that case, an error canbe shown to the user to force them to open the link on the same device. Somestate can be passed in the link to provide information on the type of operationand the user uid.

Deprecated: Differentiating email-password from email link

If you created your project on or after September 15, 2023, email enumerationprotection is enabled by default. This feature improves the security of yourproject's user accounts, but it disables the fetchSignInMethodsForEmail()method, which we formerly recommended to implement identifier-first flows.

Although you can disable email enumeration protection for your project, werecommend against doing so.

See the documentation on email enumeration protectionfor more details.

Next steps

After a user signs in for the first time, a new user account is created andlinked to the credentials—that is, the user name and password, phonenumber, or auth provider information—the user signed in with. This newaccount is stored as part of your Firebase project, and can be used to identifya user across every app in your project, regardless of how the user signs in.

  • In your apps, you can get the user's basic profile information from theFirebaseUser object. See Manage Users.

  • In your Firebase Realtime Database and Cloud Storage Security Rules, you can get the signed-in user's unique user ID from the auth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authenticationproviders by linking auth provider credentials to anexisting user account.

To sign out a user, call signOut:

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();

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.

Authenticate with Firebase Using Email Link in Android  |  Firebase Authentication (2024)
Top Articles
6 Ways To Enjoy The Wellbeing Benefits Of Silence This Season – Toulouse, France
Occupancy taxes - Airbnb Help Center
Ffxiv Act Plugin
Lexi Vonn
Breaded Mushrooms
Phone Number For Walmart Automotive Department
Tj Nails Victoria Tx
Us 25 Yard Sale Map
DL1678 (DAL1678) Delta Historial y rastreo de vuelos - FlightAware
Shaniki Hernandez Cam
All Obituaries | Ashley's J H Williams & Sons, Inc. | Selma AL funeral home and cremation
Ladyva Is She Married
Persona 4 Golden Taotie Fusion Calculator
Sarpian Cat
Dumb Money
Colts seventh rotation of thin secondary raises concerns on roster evaluation
Beau John Maloney Houston Tx
The most iconic acting lineages in cinema history
Viprow Golf
Mile Split Fl
Aldi Süd Prospekt ᐅ Aktuelle Angebote online blättern
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Dallas Mavericks 110-120 Golden State Warriors: Thompson leads Warriors to Finals, summary score, stats, highlights | Game 5 Western Conference Finals
Optum Urgent Care - Nutley Photos
T Mobile Rival Crossword Clue
Walgreens Bunce Rd
Dark Entreaty Ffxiv
Apartments / Housing For Rent near Lake Placid, FL - craigslist
Restored Republic
Downloahub
Imagetrend Elite Delaware
Desales Field Hockey Schedule
Missing 2023 Showtimes Near Grand Theatres - Bismarck
Los Amigos Taquería Kalona Menu
Metra Union Pacific West Schedule
Darrell Waltrip Off Road Center
Ishow Speed Dick Leak
The Vélodrome d'Hiver (Vél d'Hiv) Roundup
Gets Less Antsy Crossword Clue
The TBM 930 Is Another Daher Masterpiece
Cal Poly 2027 College Confidential
Lovein Funeral Obits
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Sound Of Freedom Showtimes Near Amc Mountainside 10
FedEx Authorized ShipCenter - Edouard Pack And Ship at Cape Coral, FL - 2301 Del Prado Blvd Ste 690 33990
Child care centers take steps to avoid COVID-19 shutdowns; some require masks for kids
Sapphire Pine Grove
Image Mate Orange County
Twizzlers Strawberry - 6 x 70 gram | bol
Costco Tire Promo Code Michelin 2022
La Fitness Oxford Valley Class Schedule
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5898

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.