1616
1717package 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+
2121import android .os .Bundle ;
22+ import android .os .CancellationSignal ;
2223import android .util .Log ;
2324
2425import 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 ;
3338import com .google .firebase .auth .AuthCredential ;
34- import com .google .firebase .auth .AuthResult ;
3539import com .google .firebase .auth .FirebaseAuth ;
3640import com .google .firebase .auth .FirebaseUser ;
3741import com .google .firebase .auth .GoogleAuthProvider ;
42+ import java .util .concurrent .Executors ;
3843
3944/**
4045 * Demonstrate Firebase Authentication using a Google ID Token.
4146 */
42- public class GoogleSignInActivity extends Activity {
47+ public class GoogleSignInActivity extends AppCompatActivity {
4348
4449 private static final String TAG = "GoogleActivity" ;
45- private static final int RC_SIGN_IN = 9001 ;
4650
4751 // [START declare_auth]
4852 private FirebaseAuth mAuth ;
4953 // [END declare_auth]
5054
51- private GoogleSignInClient mGoogleSignInClient ;
55+ // [START declare_credential_manager]
56+ private CredentialManager credentialManager ;
57+ // [END declare_credential_manager]
5258
5359 @ Override
5460 protected void onCreate (Bundle savedInstanceState ) {
5561 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]
6562
6663 // [START initialize_auth]
6764 // Initialize Firebase Auth
6865 mAuth = FirebaseAuth .getInstance ();
6966 // [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 ();
7074 }
7175
7276 // [START on_start_check_user]
@@ -79,55 +83,101 @@ public void onStart() {
7983 }
8084 // [END on_start_check_user]
8185
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!" );
99134 }
100135 }
101- // [END onactivityresult ]
136+ // [END handle_sign_in ]
102137
103138 // [START auth_with_google]
104139 private void firebaseAuthWithGoogle (String idToken ) {
105140 AuthCredential credential = GoogleAuthProvider .getCredential (idToken , null );
106141 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 );
120152 }
121153 });
122154 }
123155 // [END auth_with_google]
124156
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+ });
129179 }
130- // [END signin ]
180+ // [END sign_out ]
131181
132182 private void updateUI (FirebaseUser user ) {
133183
0 commit comments