Google login uses same account everytime users login

匆匆过客 提交于 2019-11-30 14:13:30
Mridul Agarwal

Just add this signIn() method after getting data from the intent.

Intent signInIntent=Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
mGoogleApiClient.clearDefaultAccountAndReconnect(); 

The simplest way is to logout the client after you handle your result (onActivityResult). Just make sure that the client is connected before you trigger the logout. Here's a snippet of my code:

private void handleGoogleLoginResult(Intent data) {
    if (data != null) {
        // get result from data received
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        int statusCode = result.getStatus().getStatusCode();
        if (result.isSuccess() && result.getSignInAccount() != null) {
            // Signed in successfully

        } 
        // logout
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        }
    }
}

Simplely workout for me

1>Activity implements GoogleApiClient.OnConnectionFailedListener {

2> mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build();

3>In OnButtonClicked

Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                startActivityForResult(signInIntent, 2);

4>

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount acct = result.getSignInAccount();
                if(acct!=null) {            
                    //Take all data You Want
                    String identifier = acct.getId()+"";                 
                    String displayName = acct.getDisplayName()+"";
                    //After You got your data add this to clear the priviously selected mail
                    mGoogleApiClient.clearDefaultAccountAndReconnect();
                }
            }else Log.e("handleSignInResult","Failed ; "+result.getStatus());
        }
    }

Those who needs it in kotlin, this worked for me, I do clear current login cache before a new login request is made

/**
 * signInGoogle
 */

private fun signInGoogle() = launch{

    //init google sigin
    val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(GOOGLE_WEBCLIENT_ID)
                .requestEmail()
                .build()



    val gApiClient = GoogleApiClient.Builder(activity)
            .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
            .build()

    val c = gApiClient.blockingConnect()

     if(c.isSuccess && gApiClient.isConnected){
         gApiClient.clearDefaultAccountAndReconnect().await()
     }

    val mGoogleSignInClient = GoogleSignIn.getClient(activity, gso)
    val signInIntent = mGoogleSignInClient.signInIntent

    //start activit
    startActivityForResult(signInIntent, GOOGLE_SIGNIN)

}//end request google login

You can view the full source here : https://github.com/transcodium/TNSMoney-Android/blob/master/app/src/main/java/com/transcodium/tnsmoney/SocialLoginActivity.kt

You needed to log out the user from google client.

public void signOut() {
   mAuth.signOut();
   mGoogleSignInClient.signOut();
   LoginManager.getInstance().logOut();
}

Where

private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;

and

mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mAuth = FirebaseAuth.getInstance();

Signout your user using:

 Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    // ...
                }
            });

I found this question while searching for a solution using the javascript client, but it might be similar with Android.

signIn({ prompt: 'select_account' })

select_account

The authorization server prompts the user to select a Google account. This allows a user who has multiple accounts to select amongst the multiple accounts that they may have current sessions for.

See https://developers.google.com/identity/sign-in/web/reference#googleauthsigninoptions.

You are not revoking user by sign out them use the following to achieve what you need :

Put this code in any activity and call it in sign out button click :

private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
        new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                // ...
            }
        });

}

write this in onCreate() :

mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();

override this in onStart() :

 @Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

Reference Link : Google Developer Page

I am using the Firebase Auth UI, and For me the fix was;

AuthUI.getInstance().setIsSmartLockEnabled(false)...

When logging in, and then;

AuthUI.signOut(context)

When Signing out

This is worked for me. !!

  @Override
            public void onPause() {
                super.onPause();
                if (mGoogleApiClient.isConnected()) {
                    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                            new ResultCallback<Status>() {
                                @Override
                                public void onResult(Status status) {
                                    // ...
                                }
                            });
                }
                mGoogleApiClient.stopAutoManage(Objects.requireNonNull(getActivity()));
                mGoogleApiClient.disconnect();

            }

if you want to enter again within the Fragment or Activity , you need to recreate these variables

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(Objects.requireNonNull(getActivity()))
                .enableAutoManage(getActivity(), (this))
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

If you are having any logout functionality. Put the below code just before your logout code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {

       CookieManager.getInstance().removeAllCookies(null);
       CookieManager.getInstance().flush();
}
else
{
       CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(activity);
       cookieSyncMngr.startSync();
       CookieManager cookieManager=CookieManager.getInstance();
       cookieManager.removeAllCookie();
       cookieManager.removeSessionCookie();
       cookieSyncMngr.stopSync();
       cookieSyncMngr.sync();
}

Hope this will help.

EDIT: you can also try replacing you storeDatainSharedPreferences method with below code:

private void storeDatainSharedPreferences() {
try {

    SharedPreferences.Editor editor = getSharedPreferences(NEW_PREFS, MODE_PRIVATE).edit();
    editor.putString("CurrentUsername", dataStore.getCurrentUserName());
    editor.putString("CurrentUserId", dataStore.getCurrentUserID());
    editor.commit();
    if(mGoogleApiClient!=null)
          mGoogleApiClient.disconnect();
}
catch (NoSuchElementException e)
{
    new AlertDialog.Builder(LoginActivity.this).setMessage("There was an error whil logging in")
            .setTitle("Little Problem here!").setPositiveButton("Retry", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent=new Intent(LoginActivity.this,LoginActivity.class);
            removeDatainSharedPreferences();
            mGoogleApiClient.disconnect();
            startActivity(intent);
        }
    }).show();
}}

Explanation : For First solution : It is the code to clear all Cookies related to your application. This can be help full in your situation because you want to clear the previous data which might be stored in Cookies.

Explanation : For Second solution : It is the code which disconnects the mGoogleApiClient. which will be helpful because You have stored the data in sharedPref now you don't need mGoogleApiClient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!