Skip to content

Commit 8e69564

Browse files
committed
Add Credential Manager to Java sample and improve Kotlin sample
1 parent c094f3a commit 8e69564

File tree

2 files changed

+117
-91
lines changed

2 files changed

+117
-91
lines changed

auth/app/src/main/java/com/google/firebase/quickstart/auth/GoogleSignInActivity.java

Lines changed: 84 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -16,57 +16,57 @@
1616

1717
package com.google.firebase.quickstart.auth;
1818

19-
import android.app.Activity;
20-
import android.content.Intent;
19+
import static com.google.android.libraries.identity.googleid.GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL;
20+
2121
import android.os.Bundle;
22+
import android.os.CancellationSignal;
2223
import android.util.Log;
23-
24-
import androidx.annotation.NonNull;
25-
26-
import com.google.android.gms.auth.api.signin.GoogleSignIn;
27-
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
28-
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
29-
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
30-
import com.google.android.gms.common.api.ApiException;
31-
import com.google.android.gms.tasks.OnCompleteListener;
32-
import com.google.android.gms.tasks.Task;
24+
import androidx.appcompat.app.AppCompatActivity;
25+
import androidx.credentials.Credential;
26+
import androidx.credentials.CredentialManager;
27+
import androidx.credentials.CredentialManagerCallback;
28+
import androidx.credentials.CustomCredential;
29+
import androidx.credentials.GetCredentialRequest;
30+
import androidx.credentials.GetCredentialResponse;
31+
import androidx.credentials.exceptions.GetCredentialException;
32+
import com.google.android.libraries.identity.googleid.GetGoogleIdOption;
33+
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential;
3334
import com.google.firebase.auth.AuthCredential;
34-
import com.google.firebase.auth.AuthResult;
3535
import com.google.firebase.auth.FirebaseAuth;
3636
import com.google.firebase.auth.FirebaseUser;
3737
import com.google.firebase.auth.GoogleAuthProvider;
38+
import java.util.concurrent.Executors;
3839

3940
/**
4041
* Demonstrate Firebase Authentication using a Google ID Token.
4142
*/
42-
public class GoogleSignInActivity extends Activity {
43+
public class GoogleSignInActivity extends AppCompatActivity {
4344

4445
private static final String TAG = "GoogleActivity";
45-
private static final int RC_SIGN_IN = 9001;
4646

4747
// [START declare_auth]
4848
private FirebaseAuth mAuth;
4949
// [END declare_auth]
5050

51-
private GoogleSignInClient mGoogleSignInClient;
51+
// [START declare_credential_manager]
52+
private CredentialManager credentialManager;
53+
// [END declare_credential_manager]
5254

5355
@Override
5456
protected void onCreate(Bundle savedInstanceState) {
5557
super.onCreate(savedInstanceState);
56-
// [START config_signin]
57-
// Configure Google Sign In
58-
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
59-
.requestIdToken(getString(R.string.default_web_client_id))
60-
.requestEmail()
61-
.build();
62-
63-
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
64-
// [END config_signin]
6558

6659
// [START initialize_auth]
6760
// Initialize Firebase Auth
6861
mAuth = FirebaseAuth.getInstance();
6962
// [END initialize_auth]
63+
64+
// [START initialize_credential_manager]
65+
// Initialize Credential Manager
66+
credentialManager = CredentialManager.create(getBaseContext());
67+
// [END initialize_credential_manager]
68+
69+
launchCredentialManager();
7070
}
7171

7272
// [START on_start_check_user]
@@ -79,56 +79,77 @@ public void onStart() {
7979
}
8080
// [END on_start_check_user]
8181

82-
// [START onactivityresult]
83-
@Override
84-
public void onActivityResult(int requestCode, int resultCode, Intent data) {
85-
super.onActivityResult(requestCode, resultCode, data);
86-
87-
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
88-
if (requestCode == RC_SIGN_IN) {
89-
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
90-
try {
91-
// Google Sign In was successful, authenticate with Firebase
92-
GoogleSignInAccount account = task.getResult(ApiException.class);
93-
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
94-
firebaseAuthWithGoogle(account.getIdToken());
95-
} catch (ApiException e) {
96-
// Google Sign In failed, update UI appropriately
97-
Log.w(TAG, "Google sign in failed", e);
98-
}
82+
// [START launch_credential_manager]
83+
private void launchCredentialManager() {
84+
// Create the configuration for the Credential Manager request
85+
GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()
86+
.setFilterByAuthorizedAccounts(true)
87+
.setServerClientId(getBaseContext().getString(R.string.default_web_client_id))
88+
.build();
89+
90+
// Create the Credential Manager request using the configuration created above
91+
GetCredentialRequest request = new GetCredentialRequest.Builder()
92+
.addCredentialOption(googleIdOption)
93+
.build();
94+
95+
// Launch Credential Manager UI
96+
credentialManager.getCredentialAsync(
97+
getBaseContext(),
98+
request,
99+
new CancellationSignal(),
100+
Executors.newSingleThreadExecutor(),
101+
new CredentialManagerCallback<>() {
102+
@Override
103+
public void onResult(GetCredentialResponse result) {
104+
// Extract credential from the result returned by Credential Manager
105+
createGoogleIdToken(result.getCredential());
106+
}
107+
108+
@Override
109+
public void onError(GetCredentialException e) {
110+
Log.e(TAG, "Couldn't retrieve user's credentials: " + e.getLocalizedMessage());
111+
}
112+
}
113+
);
114+
}
115+
// [END launch_credential_manager]
116+
117+
// [START create_google_id_token]
118+
private void createGoogleIdToken(Credential credential) {
119+
// Check if credential is of type Google ID
120+
if (credential instanceof CustomCredential customCredential
121+
&& credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)) {
122+
// Create Google ID Token
123+
Bundle credentialData = customCredential.getData();
124+
GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credentialData);
125+
126+
// Sign in to Firebase with using the token
127+
firebaseAuthWithGoogle(googleIdTokenCredential.getIdToken());
128+
} else {
129+
Log.d(TAG, "Credential is not of type Google ID!");
99130
}
100131
}
101-
// [END onactivityresult]
132+
// [END create_google_id_token]
102133

103134
// [START auth_with_google]
104135
private void firebaseAuthWithGoogle(String idToken) {
105136
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
106137
mAuth.signInWithCredential(credential)
107-
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
108-
@Override
109-
public void onComplete(@NonNull Task<AuthResult> task) {
110-
if (task.isSuccessful()) {
111-
// Sign in success, update UI with the signed-in user's information
112-
Log.d(TAG, "signInWithCredential:success");
113-
FirebaseUser user = mAuth.getCurrentUser();
114-
updateUI(user);
115-
} else {
116-
// If sign in fails, display a message to the user.
117-
Log.w(TAG, "signInWithCredential:failure", task.getException());
118-
updateUI(null);
119-
}
138+
.addOnCompleteListener(this, task -> {
139+
if (task.isSuccessful()) {
140+
// Sign in success, update UI with the signed-in user's information
141+
Log.d(TAG, "signInWithCredential:success");
142+
FirebaseUser user = mAuth.getCurrentUser();
143+
updateUI(user);
144+
} else {
145+
// If sign in fails, display a message to the user
146+
Log.w(TAG, "signInWithCredential:failure", task.getException());
147+
updateUI(null);
120148
}
121149
});
122150
}
123151
// [END auth_with_google]
124152

125-
// [START signin]
126-
private void signIn() {
127-
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
128-
startActivityForResult(signInIntent, RC_SIGN_IN);
129-
}
130-
// [END signin]
131-
132153
private void updateUI(FirebaseUser user) {
133154

134155
}

auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package com.google.firebase.quickstart.auth.kotlin
33
import android.os.Bundle
44
import android.util.Log
55
import androidx.appcompat.app.AppCompatActivity
6+
import androidx.credentials.Credential
67
import androidx.credentials.CredentialManager
78
import androidx.credentials.CustomCredential
89
import androidx.credentials.GetCredentialRequest
@@ -45,20 +46,7 @@ class GoogleSignInActivity : AppCompatActivity() {
4546
credentialManager = CredentialManager.create(baseContext)
4647
// [END initialize_credential_manager]
4748

48-
// [START configure_credential_manager]
49-
// Create the configuration for the Credential Manager request
50-
val googleIdOption = GetGoogleIdOption.Builder()
51-
.setFilterByAuthorizedAccounts(true)
52-
.setServerClientId(baseContext.getString(R.string.default_web_client_id))
53-
.build()
54-
55-
// Create the Credential Manager request using the configuration created above
56-
val request = GetCredentialRequest.Builder()
57-
.addCredentialOption(googleIdOption)
58-
.build()
59-
// [END configure_credential_manager]
60-
61-
getCredential(request)
49+
launchCredentialManager()
6250
}
6351

6452
// [START on_start_check_user]
@@ -70,8 +58,19 @@ class GoogleSignInActivity : AppCompatActivity() {
7058
}
7159
// [END on_start_check_user]
7260

73-
// [START get_user_credential]
74-
private fun getCredential(request: GetCredentialRequest) {
61+
// [START launch_credential_manager]
62+
private fun launchCredentialManager() {
63+
// Create the configuration for the Credential Manager request
64+
val googleIdOption = GetGoogleIdOption.Builder()
65+
.setFilterByAuthorizedAccounts(true)
66+
.setServerClientId(baseContext.getString(R.string.default_web_client_id))
67+
.build()
68+
69+
// Create the Credential Manager request using the configuration created above
70+
val request = GetCredentialRequest.Builder()
71+
.addCredentialOption(googleIdOption)
72+
.build()
73+
7574
lifecycleScope.launch {
7675
try {
7776
// Launch Credential Manager UI
@@ -81,22 +80,28 @@ class GoogleSignInActivity : AppCompatActivity() {
8180
)
8281

8382
// Extract credential from the result returned by Credential Manager
84-
val credential = result.credential
85-
86-
// Check if credential is of type Google ID
87-
if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
88-
val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
89-
// Sign in to Firebase with the Google ID Token
90-
firebaseAuthWithGoogle(googleIdTokenCredential.idToken)
91-
} else {
92-
Log.d(TAG, "Credential is not of type Google ID!")
93-
}
83+
createGoogleIdToken(result.credential)
9484
} catch (e: GetCredentialException) {
9585
Log.e(TAG, "Couldn't retrieve user's credentials: ${e.localizedMessage}")
9686
}
9787
}
9888
}
99-
// [END get_user_credential]
89+
// [END launch_credential_manager]
90+
91+
// [START create_google_id_token]
92+
private fun createGoogleIdToken(credential: Credential) {
93+
// Check if credential is of type Google ID
94+
if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
95+
// Create Google ID Token
96+
val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
97+
98+
// Sign in to Firebase with using the token
99+
firebaseAuthWithGoogle(googleIdTokenCredential.idToken)
100+
} else {
101+
Log.d(TAG, "Credential is not of type Google ID!")
102+
}
103+
}
104+
// [END create_google_id_token]
100105

101106
// [START auth_with_google]
102107
private fun firebaseAuthWithGoogle(idToken: String) {
@@ -109,7 +114,7 @@ class GoogleSignInActivity : AppCompatActivity() {
109114
val user = auth.currentUser
110115
updateUI(user)
111116
} else {
112-
// If sign in fails, display a message to the user.
117+
// If sign in fails, display a message to the user
113118
Log.w(TAG, "signInWithCredential:failure", task.exception)
114119
updateUI(null)
115120
}

0 commit comments

Comments
 (0)