Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions auth/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ dependencies {
// [START gradle_firebase_ui_auth]
implementation("com.firebaseui:firebase-ui-auth:8.0.2")

// Google Identity Services SDK (only required for Auth with Google)
implementation("androidx.credentials:credentials:1.3.0")
implementation("androidx.credentials:credentials-play-services-auth:1.3.0")
implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")

// 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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,57 +16,61 @@

package com.google.firebase.quickstart.auth;

import android.app.Activity;
import android.content.Intent;
import static com.google.android.libraries.identity.googleid.GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL;

import android.os.Bundle;
import android.os.CancellationSignal;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import androidx.appcompat.app.AppCompatActivity;
import androidx.credentials.ClearCredentialStateRequest;
import androidx.credentials.Credential;
import androidx.credentials.CredentialManager;
import androidx.credentials.CredentialManagerCallback;
import androidx.credentials.CustomCredential;
import androidx.credentials.GetCredentialRequest;
import androidx.credentials.GetCredentialResponse;
import androidx.credentials.exceptions.ClearCredentialException;
import androidx.credentials.exceptions.GetCredentialException;
import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.util.concurrent.Executors;

/**
* Demonstrate Firebase Authentication using a Google ID Token.
*/
public class GoogleSignInActivity extends Activity {
public class GoogleSignInActivity extends AppCompatActivity {

private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;

// [START declare_auth]
private FirebaseAuth mAuth;
// [END declare_auth]

private GoogleSignInClient mGoogleSignInClient;
// [START declare_credential_manager]
private CredentialManager credentialManager;
// [END declare_credential_manager]

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// [START config_signin]
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();

mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// [END config_signin]

// [START initialize_auth]
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
// [END initialize_auth]

// [START initialize_credential_manager]
// Initialize Credential Manager
credentialManager = CredentialManager.create(getBaseContext());
// [END initialize_credential_manager]

launchCredentialManager();
}

// [START on_start_check_user]
Expand All @@ -79,55 +83,98 @@ public void onStart() {
}
// [END on_start_check_user]

// [START onactivityresult]
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
}
private void launchCredentialManager() {
// [START create_credential_manager_request]
// Instantiate a Google sign-in request
GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()
.setFilterByAuthorizedAccounts(true)
.setServerClientId(getBaseContext().getString(R.string.default_web_client_id))
.build();

// Create the Credential Manager request
GetCredentialRequest request = new GetCredentialRequest.Builder()
.addCredentialOption(googleIdOption)
.build();
// [END create_credential_manager_request]

// Launch Credential Manager UI
credentialManager.getCredentialAsync(
getBaseContext(),
request,
new CancellationSignal(),
Executors.newSingleThreadExecutor(),
new CredentialManagerCallback<>() {
@Override
public void onResult(GetCredentialResponse result) {
// Extract credential from the result returned by Credential Manager
createGoogleIdToken(result.getCredential());
}

@Override
public void onError(GetCredentialException e) {
Log.e(TAG, "Couldn't retrieve user's credentials: " + e.getLocalizedMessage());
}
}
);
}

// [START create_google_id_token]
private void createGoogleIdToken(Credential credential) {
// Check if credential is of type Google ID
if (credential instanceof CustomCredential customCredential
&& credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)) {
// Create Google ID Token
Bundle credentialData = customCredential.getData();
GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credentialData);

// Sign in to Firebase with using the token
firebaseAuthWithGoogle(googleIdTokenCredential.getIdToken());
} else {
Log.w(TAG, "Credential is not of type Google ID!");
}
}
// [END onactivityresult]
// [END create_google_id_token]

// [START auth_with_google]
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
updateUI(null);
}
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user
Log.w(TAG, "signInWithCredential:failure", task.getException());
updateUI(null);
}
});
}
// [END auth_with_google]

// [START signin]
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
// [START clear_credential_stage]
private void clearCredentialState() {
// When a user signs out, clear the current user credential state from all credential providers.
ClearCredentialStateRequest clearRequest = new ClearCredentialStateRequest();
credentialManager.clearCredentialStateAsync(
clearRequest,
new CancellationSignal(),
Executors.newSingleThreadExecutor(),
new CredentialManagerCallback<>() {
@Override
public void onResult(@NonNull Void result) {
updateUI(null);
}

@Override
public void onError(@NonNull ClearCredentialException e) {
Log.e(TAG, "Couldn't clear user credentials: " + e.getLocalizedMessage());
}
});
}
// [END signin]
// [END clear_credential_stage]

private void updateUI(FirebaseUser user) {

Expand Down
Loading