android-studio
  1. android-studio-firebase-authentication-google-login

Android Studio Firebase Authentication - Google Login

Firebase Authentication is a popular and easy-to-use authentication service provided by Google. It enables you to add authentication to your mobile app easily and quickly, and Google Login is one of the authentication methods provided by Firebase Authentication.

Syntax

The following code snippet demonstrates the basic syntax of Google Login in Firebase Authentication.

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build();

GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, gso);

Example

The following example shows how to implement Google Login in Firebase Authentication in an Android app.

    private GoogleSignInClient mGoogleSignInClient;
    private FirebaseAuth mAuth;

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

        mAuth = FirebaseAuth.getInstance();

        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.sign_in_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
        }
    }

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

    @Override
    public 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 account) {
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);

        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            updateUI(null);
                        }
                    }
                });
    }

    private void updateUI(FirebaseUser user) {
        if (user != null) {
            Toast.makeText(this, "Google sign in success: " + user.getEmail(), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Google sign in failed.", Toast.LENGTH_SHORT).show();
        }
    }

Output

Upon successful Google Login, the user's email address is displayed in a toast message, as shown below.

Firebase Authentication - Google Login

Explanation

Here's a brief explanation of the various components used in the above example:

  • GoogleSignInOptions: The GoogleSignInOptions object is used to configure the Google sign-in options. The DEFAULT_SIGN_IN parameter specifies the default sign-in behavior, and requestIdToken and requestEmail are used to request an ID token and email from the user during sign-in.
  • GoogleSignInClient: The GoogleSignInClient object is used to initiate the Google sign-in flow, and its getSignInIntent() method returns an Intent that starts the Google sign-in activity.
  • firebaseAuthWithGoogle: This method takes the Google sign-in credentials and uses them to authenticate with Firebase Authentication. If the authentication is successful, it calls updateUI with the user's information and displays a toast message.
  • updateUI: This method is used to update the user interface after sign-in. If the user is authenticated, it displays the user's email address in a toast message. Otherwise, it displays a failure message.

Use

To use Google Login in Firebase Authentication, you'll need to follow these steps:

  1. Configure Firebase Authentication and enable Google sign-in.
  2. Add the necessary dependencies to your app build.gradle file.
  3. Implement the code for Google Login as described in the example above.

Important Points

Here are some important points to keep in mind while implementing Google Login in Firebase Authentication:

  • You must create a project in the Firebase console and enable Firebase Authentication before you can use Firebase Authentication in your app.
  • You must add the appropriate dependencies to your app build.gradle file in order to use Firebase Authentication.
  • You must configure Google sign-in in the Firebase console and add the necessary configuration files to your app.
  • You must authenticate with Firebase Authentication using the same credentials provided by Google sign-in.

Summary

In this tutorial, we learned how to implement Google Login in Firebase Authentication using Android Studio. We covered the syntax, example code, output, explanation, use cases, important points and summary to help you get started with Firebase Authentication in your own app.

Published on: