Firebase Authentication in Android – User Sign-Ups, Logins, and Authentication - Textnotes

Firebase Authentication in Android – User Sign-Ups, Logins, and Authentication


Learn how to integrate Firebase Authentication in your Android app to handle user sign-ups, logins, and authentication through multiple methods such as email/password, Google Sign-In, and Facebook Login.

Firebase Authentication provides backend services to help authenticate users, including simple pass-through authentication using email and password, third-party providers like Google, Facebook, and Twitter, and more. It also integrates with other Firebase services to provide a seamless experience for user management.

i) Setting Up Firebase Authentication in Android

To get started with Firebase Authentication in your Android project, follow these steps:

Step 1: Add Firebase to Your Android Project

  1. Go to the Firebase Console: Firebase Console.
  2. Create a new project or select an existing one.
  3. Add your Android app to the Firebase project by entering your app's package name.
  4. Download the google-services.json file and place it in the app/ directory of your Android project.
  5. Add the required Firebase dependencies to your build.gradle files.

In your project-level build.gradle file, add:


classpath 'com.google.gms:google-services:4.3.10' // Firebase Services plugin

In your app-level build.gradle file, add:


dependencies {
implementation 'com.google.firebase:firebase-auth:21.0.1' // Firebase Authentication
}

Then sync the project with Gradle.

Step 2: Enable Firebase Authentication Method

  1. In the Firebase Console, go to Authentication and enable the sign-in methods you want to support (email/password, Google Sign-In, Facebook Login, etc.).
  2. For Google Sign-In and Facebook Login, you will need to set up their respective credentials in the Firebase Console.

ii) Email and Password Authentication

Email and Password Authentication is one of the simplest forms of authentication. Firebase provides methods to create new users and sign in existing users using email and password.

Sign Up a New User with Email and Password


FirebaseAuth.getInstance().createUserWithEmailAndPassword("user@example.com", "password123")
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = FirebaseAuth.getInstance().currentUser
// Proceed with the authenticated user
Log.d("Firebase", "User created successfully: ${user?.email}")
} else {
Log.e("Firebase", "Error: ${task.exception?.message}")
}
}

Sign In an Existing User


FirebaseAuth.getInstance().signInWithEmailAndPassword("user@example.com", "password123")
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = FirebaseAuth.getInstance().currentUser
// Proceed with the authenticated user
Log.d("Firebase", "User signed in successfully: ${user?.email}")
} else {
Log.e("Firebase", "Error: ${task.exception?.message}")
}
}

Sign Out

To sign the user out of the app:


FirebaseAuth.getInstance().signOut()

iii) Google Sign-In Authentication

Google Sign-In is a popular authentication method where users can log in using their Google account.

Step 1: Add Google Sign-In to Firebase

  1. In the Firebase Console, enable Google Sign-In under the Authentication section.
  2. Ensure that you’ve set up a Web client ID in the Google Developer Console.

Step 2: Set Up Google Sign-In in Android

Add the necessary dependencies to your app-level build.gradle file:


implementation 'com.google.android.gms:play-services-auth:19.2.0' // Google Sign-In

Set up Google Sign-In:


val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)) // Web client ID from Firebase
.requestEmail()
.build()

val googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions)

val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)

Handle the result of the Google Sign-In:


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
// Authenticate with Firebase
firebaseAuthWithGoogle(account.idToken)
} catch (e: ApiException) {
Log.e("Google Sign-In", "signInResult:failed code=" + e.statusCode)
}
}
}

private fun firebaseAuthWithGoogle(idToken: String?) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
FirebaseAuth.getInstance().signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = FirebaseAuth.getInstance().currentUser
// Proceed with authenticated user
Log.d("Firebase", "Google Sign-In successful: ${user?.email}")
} else {
Log.e("Firebase", "Error: ${task.exception?.message}")
}
}
}

iv) Facebook Login Authentication

Firebase also supports Facebook Login for authentication. To integrate Facebook Login, you will need to:

  1. Enable Facebook authentication in the Firebase Console.
  2. Set up Facebook SDK in your Android project.
  3. Link Facebook login credentials with Firebase.

Step 1: Set Up Facebook SDK

Add the dependencies for Facebook SDK to your app-level build.gradle file:


implementation 'com.facebook.android:facebook-android-sdk:12.0.0' // Facebook SDK

Step 2: Configure Facebook Login

In your MainActivity:


val callbackManager = CallbackManager.Factory.create()

LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult?) {
val accessToken = result?.accessToken
val credential = FacebookAuthProvider.getCredential(accessToken?.token ?: "")
FirebaseAuth.getInstance().signInWithCredential(credential)
.addOnCompleteListener(this@MainActivity) { task ->
if (task.isSuccessful) {
val user = FirebaseAuth.getInstance().currentUser
Log.d("Firebase", "Facebook Login successful: ${user?.email}")
} else {
Log.e("Firebase", "Error: ${task.exception?.message}")
}
}
}

override fun onCancel() {
Log.d("Facebook", "Login cancelled")
}

override fun onError(error: FacebookException?) {
Log.e("Facebook", "Login error: ${error?.message}")
}
})

v) Other Authentication Providers

Firebase also supports authentication with various other providers, such as:

  1. Twitter
  2. GitHub
  3. Phone Authentication

You can enable these providers in the Firebase Console and implement them similarly as shown for Google and Facebook.

vi) Firebase Authentication – Benefits

  1. Multiple Authentication Providers:
  2. Firebase supports multiple authentication methods such as email/password, Google, Facebook, Twitter, and more, providing flexibility in how users sign in to your app.
  3. Easy Integration:
  4. Firebase Authentication is simple to integrate into Android apps and handles much of the heavy lifting involved in user authentication, including credential management and session handling.
  5. Backend Authentication:
  6. Firebase handles the authentication process on the backend, ensuring that passwords and sensitive data are securely managed.
  7. Security:
  8. Firebase Authentication uses secure token-based authentication (JWT) and supports email verification and password resets, providing a secure way to manage users.
  9. Unified SDK:
  10. Firebase Authentication provides a unified SDK to integrate authentication across all platforms (iOS, Android, Web).

vii) Conclusion

In this tutorial, we’ve learned how to integrate Firebase Authentication into an Android app. Whether you’re using email/password, Google Sign-In, Facebook Login, or other third-party providers, Firebase provides a simple and secure way to manage authentication in your app.

Firebase Authentication makes it easy to implement secure sign-up and login functionality without worrying about the complexities of backend authentication, allowing you to focus on app functionality and user experience.