16
16
17
17
package com .google .firebase .quickstart .auth ;
18
18
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
+
21
21
import android .os .Bundle ;
22
+ import android .os .CancellationSignal ;
22
23
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 ;
33
34
import com .google .firebase .auth .AuthCredential ;
34
- import com .google .firebase .auth .AuthResult ;
35
35
import com .google .firebase .auth .FirebaseAuth ;
36
36
import com .google .firebase .auth .FirebaseUser ;
37
37
import com .google .firebase .auth .GoogleAuthProvider ;
38
+ import java .util .concurrent .Executors ;
38
39
39
40
/**
40
41
* Demonstrate Firebase Authentication using a Google ID Token.
41
42
*/
42
- public class GoogleSignInActivity extends Activity {
43
+ public class GoogleSignInActivity extends AppCompatActivity {
43
44
44
45
private static final String TAG = "GoogleActivity" ;
45
- private static final int RC_SIGN_IN = 9001 ;
46
46
47
47
// [START declare_auth]
48
48
private FirebaseAuth mAuth ;
49
49
// [END declare_auth]
50
50
51
- private GoogleSignInClient mGoogleSignInClient ;
51
+ // [START declare_credential_manager]
52
+ private CredentialManager credentialManager ;
53
+ // [END declare_credential_manager]
52
54
53
55
@ Override
54
56
protected void onCreate (Bundle savedInstanceState ) {
55
57
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]
65
58
66
59
// [START initialize_auth]
67
60
// Initialize Firebase Auth
68
61
mAuth = FirebaseAuth .getInstance ();
69
62
// [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 ();
70
70
}
71
71
72
72
// [START on_start_check_user]
@@ -79,56 +79,77 @@ public void onStart() {
79
79
}
80
80
// [END on_start_check_user]
81
81
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!" );
99
130
}
100
131
}
101
- // [END onactivityresult ]
132
+ // [END create_google_id_token ]
102
133
103
134
// [START auth_with_google]
104
135
private void firebaseAuthWithGoogle (String idToken ) {
105
136
AuthCredential credential = GoogleAuthProvider .getCredential (idToken , null );
106
137
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 );
120
148
}
121
149
});
122
150
}
123
151
// [END auth_with_google]
124
152
125
- // [START signin]
126
- private void signIn () {
127
- Intent signInIntent = mGoogleSignInClient .getSignInIntent ();
128
- startActivityForResult (signInIntent , RC_SIGN_IN );
129
- }
130
- // [END signin]
131
-
132
153
private void updateUI (FirebaseUser user ) {
133
154
134
155
}
0 commit comments