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
24
25
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 ;
26
+ import androidx .appcompat .app .AppCompatActivity ;
27
+ import androidx .credentials .ClearCredentialStateRequest ;
28
+ import androidx .credentials .Credential ;
29
+ import androidx .credentials .CredentialManager ;
30
+ import androidx .credentials .CredentialManagerCallback ;
31
+ import androidx .credentials .CustomCredential ;
32
+ import androidx .credentials .GetCredentialRequest ;
33
+ import androidx .credentials .GetCredentialResponse ;
34
+ import androidx .credentials .exceptions .ClearCredentialException ;
35
+ import androidx .credentials .exceptions .GetCredentialException ;
36
+ import com .google .android .libraries .identity .googleid .GetGoogleIdOption ;
37
+ import com .google .android .libraries .identity .googleid .GoogleIdTokenCredential ;
33
38
import com .google .firebase .auth .AuthCredential ;
34
- import com .google .firebase .auth .AuthResult ;
35
39
import com .google .firebase .auth .FirebaseAuth ;
36
40
import com .google .firebase .auth .FirebaseUser ;
37
41
import com .google .firebase .auth .GoogleAuthProvider ;
42
+ import java .util .concurrent .Executors ;
38
43
39
44
/**
40
45
* Demonstrate Firebase Authentication using a Google ID Token.
41
46
*/
42
- public class GoogleSignInActivity extends Activity {
47
+ public class GoogleSignInActivity extends AppCompatActivity {
43
48
44
49
private static final String TAG = "GoogleActivity" ;
45
- private static final int RC_SIGN_IN = 9001 ;
46
50
47
51
// [START declare_auth]
48
52
private FirebaseAuth mAuth ;
49
53
// [END declare_auth]
50
54
51
- private GoogleSignInClient mGoogleSignInClient ;
55
+ // [START declare_credential_manager]
56
+ private CredentialManager credentialManager ;
57
+ // [END declare_credential_manager]
52
58
53
59
@ Override
54
60
protected void onCreate (Bundle savedInstanceState ) {
55
61
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
62
66
63
// [START initialize_auth]
67
64
// Initialize Firebase Auth
68
65
mAuth = FirebaseAuth .getInstance ();
69
66
// [END initialize_auth]
67
+
68
+ // [START initialize_credential_manager]
69
+ // Initialize Credential Manager
70
+ credentialManager = CredentialManager .create (getBaseContext ());
71
+ // [END initialize_credential_manager]
72
+
73
+ launchCredentialManager ();
70
74
}
71
75
72
76
// [START on_start_check_user]
@@ -79,55 +83,101 @@ public void onStart() {
79
83
}
80
84
// [END on_start_check_user]
81
85
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
- }
86
+ private void launchCredentialManager () {
87
+ // [START create_credential_manager_request]
88
+ // Instantiate a Google sign-in request
89
+ GetGoogleIdOption googleIdOption = new GetGoogleIdOption .Builder ()
90
+ .setFilterByAuthorizedAccounts (true )
91
+ .setServerClientId (getString (R .string .default_web_client_id ))
92
+ .build ();
93
+
94
+ // Create the Credential Manager request
95
+ GetCredentialRequest request = new GetCredentialRequest .Builder ()
96
+ .addCredentialOption (googleIdOption )
97
+ .build ();
98
+ // [END create_credential_manager_request]
99
+
100
+ // Launch Credential Manager UI
101
+ credentialManager .getCredentialAsync (
102
+ getBaseContext (),
103
+ request ,
104
+ new CancellationSignal (),
105
+ Executors .newSingleThreadExecutor (),
106
+ new CredentialManagerCallback <>() {
107
+ @ Override
108
+ public void onResult (GetCredentialResponse result ) {
109
+ // Extract credential from the result returned by Credential Manager
110
+ handleSignIn (result .getCredential ());
111
+ }
112
+
113
+ @ Override
114
+ public void onError (GetCredentialException e ) {
115
+ Log .e (TAG , "Couldn't retrieve user's credentials: " + e .getLocalizedMessage ());
116
+ }
117
+ }
118
+ );
119
+ }
120
+
121
+ // [START handle_sign_in]
122
+ private void handleSignIn (Credential credential ) {
123
+ // Check if credential is of type Google ID
124
+ if (credential instanceof CustomCredential customCredential
125
+ && credential .getType ().equals (TYPE_GOOGLE_ID_TOKEN_CREDENTIAL )) {
126
+ // Create Google ID Token
127
+ Bundle credentialData = customCredential .getData ();
128
+ GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential .createFrom (credentialData );
129
+
130
+ // Sign in to Firebase with using the token
131
+ firebaseAuthWithGoogle (googleIdTokenCredential .getIdToken ());
132
+ } else {
133
+ Log .w (TAG , "Credential is not of type Google ID!" );
99
134
}
100
135
}
101
- // [END onactivityresult ]
136
+ // [END handle_sign_in ]
102
137
103
138
// [START auth_with_google]
104
139
private void firebaseAuthWithGoogle (String idToken ) {
105
140
AuthCredential credential = GoogleAuthProvider .getCredential (idToken , null );
106
141
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
- }
142
+ .addOnCompleteListener (this , task -> {
143
+ if (task .isSuccessful ()) {
144
+ // Sign in success, update UI with the signed-in user's information
145
+ Log .d (TAG , "signInWithCredential:success" );
146
+ FirebaseUser user = mAuth .getCurrentUser ();
147
+ updateUI (user );
148
+ } else {
149
+ // If sign in fails, display a message to the user
150
+ Log .w (TAG , "signInWithCredential:failure" , task .getException ());
151
+ updateUI (null );
120
152
}
121
153
});
122
154
}
123
155
// [END auth_with_google]
124
156
125
- // [START signin]
126
- private void signIn () {
127
- Intent signInIntent = mGoogleSignInClient .getSignInIntent ();
128
- startActivityForResult (signInIntent , RC_SIGN_IN );
157
+ // [START sign_out]
158
+ private void signOut () {
159
+ // Firebase sign out
160
+ mAuth .signOut ();
161
+
162
+ // When a user signs out, clear the current user credential state from all credential providers.
163
+ ClearCredentialStateRequest clearRequest = new ClearCredentialStateRequest ();
164
+ credentialManager .clearCredentialStateAsync (
165
+ clearRequest ,
166
+ new CancellationSignal (),
167
+ Executors .newSingleThreadExecutor (),
168
+ new CredentialManagerCallback <>() {
169
+ @ Override
170
+ public void onResult (@ NonNull Void result ) {
171
+ updateUI (null );
172
+ }
173
+
174
+ @ Override
175
+ public void onError (@ NonNull ClearCredentialException e ) {
176
+ Log .e (TAG , "Couldn't clear user credentials: " + e .getLocalizedMessage ());
177
+ }
178
+ });
129
179
}
130
- // [END signin ]
180
+ // [END sign_out ]
131
181
132
182
private void updateUI (FirebaseUser user ) {
133
183
0 commit comments