Firebase Authentication

Papon Ahasan
4 min readFeb 7, 2023

Dependency Add

In your module (app-level) Gradle file (/build.gradle), add the dependency for the Firebase Authentication Android library.

dependencies {
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:31.2.0')

//When using the BoM, you don't specify versions
implementation 'com.google.firebase:firebase-auth-ktx'

// [START gradle_firebase_ui_auth]
implementation "com.firebaseui:firebase-ui-auth:8.0.2"

// Required only if Facebook login support is required
// Find the latest Facebook SDK releases here: https://goo.gl/Ce5L94
implementation "com.facebook.android:facebook-android-sdk:4.42.0"

//Google Play services library and specify its version
implementation 'com.google.android.gms:play-services-auth:20.4.1'
}

Authentication Services

01. Sign-in providers: In the Firebase console, open the Authentication section enabling your first sign-in method

02. If you support Google Sign-in and haven’t yet specified your app’s SHA-1 fingerprint, do so from the Settings page of the Firebase console. See Authenticating Your Client for details on how to get your app’s SHA-1 fingerprint.

You can also get the SHA-1 of your signing certificate using the Gradle signingReport command:

./gradlew signingReport

03. If you support sign-in with Facebook or Twitter, add string resources to strings.xml that specify the identifying information required by each provider:

<resources>
<!-- Facebook application ID and custom URL scheme (app ID prefixed by 'fb'). -->
<string name="facebook_application_id" translatable="false">YOUR_APP_ID</string>
<string name="facebook_login_protocol_scheme" translatable="false">fbYOUR_APP_ID</string>
</resources>

Sign in with EmailPassword

Sign in with Google

Demonstrate Firebase Authentication using a Google ID Token.

  • XML Desing
<com.google.android.gms.common.SignInButton
android:id="@+id/signInBtn"
android:layout_width="match_parent"
android:layout_margin="16dp"
android:layout_gravity="center"
android:layout_height="wrap_content"/>
  • Activity
1) onViewCreated()
2) onStart()
3) updateUI()

Then click

4) signIn()
5) onActivityResult()
6) firebaseAuthWithGoogle()
7) updateUI()

After SignIn

1)onViewCreated()
2)onStart()
3)updateUI()
[START declare_auth]
private lateinit var auth: FirebaseAuth

private lateinit var googleSignInClient: GoogleSignInClient

companion object {
private const val TAG = "GoogleActivity"
private const val RC_SIGN_IN = 9001
}

[START config_signin]

You must pass your “server” client ID to the Credentials page. To find the OAuth 2.0 client ID: The Web application type client ID is your backend server’s OAuth 2.0 client ID

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

binding.signInBtn.setOnClickListener {
signIn()
}
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()

googleSignInClient = activity?.let { GoogleSignIn.getClient(it, gso) }!!

// Initialize Firebase Auth
auth = Firebase.auth

}

[START on_start_check_user]

override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
private fun updateUI(user: FirebaseUser?) {
if(user!=null) {
Toast.makeText(context,"ok",Toast.LENGTH_LONG).show()
activity?.let { Navigation.findNavController(it, R.id.fragmentContainerView) }
?.navigate(R.id.homeFragment)
}
}

[START signin]

private fun signIn() {
val signInIntent = googleSignInClient.signInIntent

/*01.The new way (Kotlin)*/
resultLauncher.launch(signInIntent)

/*02.The old way*/
startActivityForResult(signInIntent, RC_SIGN_IN)
}

[START onactivityresult]


/* 01. The new way (Kotlin) */
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes

val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
}
}
}

/* 02.The old way:*/

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
}
}
}

[START auth_with_google]

/* recommendated */
/*coroutines (Background Thread)*/

private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
GlobalScope.launch(Dispatchers.IO){
auth.signInWithCredential(credential).await()
val user = auth.currentUser
withContext(Dispatchers.Main){
updateUI(user)
}
}
}

/* OR Not-Recommendated
(Main Thread)*/

private fun firebaseAuthWithGoogle(idToken: String) {
activity?.let {
auth.signInWithCredential(credential)
.addOnCompleteListener(it) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
updateUI(null)
}
}
}
}

Use the Firebase Authentication SDK to sign in the user and obtain the id_token. Below is a simplified example using Firebase Authentication

// Import necessary Firebase libraries
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

// ...

// Create an instance of FirebaseAuth
FirebaseAuth mAuth = FirebaseAuth.getInstance();

// Start the Google Sign-In intent
private void signInWithGoogle() {
// Implement your Google Sign-In logic here
// ...

// After successful sign-in, get the user's ID token
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
currentUser.getIdToken(true)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
// Get the ID token
String idToken = task.getResult().getToken();
// Use the idToken as needed (e.g., pass it to your server)
// ...
} else {
// Handle the exception
Exception exception = task.getException();
exception.printStackTrace();
}
});
}
}

Ref

--

--