Cover Image for Firebase Authentication – Google Login in Android
223 views

Firebase Authentication – Google Login in Android

Firebase Authentication provides a straightforward way to implement Google Login in your Android app. This allows users to log in using their Google accounts, making the login process convenient and secure. Here’s a step-by-step guide on how to integrate Google Login using Firebase Authentication:

1. Set Up Firebase Project:

  • Go to the Firebase Console (https://console.firebase.google.com/).
  • Click “Add Project” and follow the setup wizard to create a new Firebase project.
  • After creating the project, click on it to access the project dashboard.

2. Add Your App to Firebase:

  • Click on “Add app” and select the appropriate platform (Android in this case).
  • Follow the setup instructions to register your app with Firebase. You’ll need to provide your app’s package name, app nickname, and SHA-1 certificate fingerprint (required for Google Sign-In).
  • Download the google-services.json file and add it to your app module’s directory.

3. Add Dependencies:

In your app-level build.gradle file, add the Firebase Authentication and Google Sign-In dependencies:

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

Sync your project to ensure that the dependencies are downloaded.

4. Configure OAuth Consent Screen:

  • In the Firebase Console, navigate to “Authentication” > “Sign-in method.”
  • Enable “Google” as a sign-in provider.
  • Configure the OAuth consent screen with required details like app name, user support email, and other necessary information.

5. Implement Google Login in Your Android App:

Now, you need to implement Google Sign-In in your Android app. Below is a basic example:

a. Add Google Sign-In Button:

In your layout XML file (e.g., activity_main.xml), add a button that allows users to initiate Google Sign-In:

XML
<com.google.android.gms.common.SignInButton
    android:id="@+id/googleSignInButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

b. Implement Google Sign-In Logic:

In your activity or fragment, initialize GoogleSignInOptions and GoogleSignInClient, and attach an onClickListener to your sign-in button:

Java
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;

public class MainActivity extends AppCompatActivity {

    private GoogleSignInClient mGoogleSignInClient;
    private FirebaseAuth mAuth;
    private static final int RC_SIGN_IN = 123; // Request code for sign-in

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();

        // Configure Google Sign-In options
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        findViewById(R.id.googleSignInButton).setOnClickListener(view -> signInWithGoogle());
    }

    private void signInWithGoogle() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Log.w(TAG, "Google sign-in failed", e);
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        FirebaseUser user = mAuth.getCurrentUser();
                        // User is signed in, you can update UI or navigate to the next activity.
                    } else {
                        // Sign-in failed, handle the error.
                    }
                });
    }
}

Make sure to replace R.string.default_web_client_id with your own Web client ID from the Firebase Console.

6. Testing and UI Customization:

Test your Google Sign-In implementation thoroughly on different devices and customize the user interface and user experience as needed.

With these steps, you can integrate Google Login using Firebase Authentication in your Android app, allowing users to log in with their Google accounts easily and securely.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS