每次用户登录时,Google登录都使用相同的帐户

时间:2016-04-16 03:21:34

标签: android oauth-2.0 google-login

我使用OAuth让用户通过Google帐户登录Android应用。当用户第一次点击Google登录按钮时,会生成一个用于选择帐户的对话框。同样,当用户退出并决定使用其他Google帐户登录时,它不会提示选择该帐户,它会记录用户之前选择的帐户

'

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    initialize();
    Firebase.setAndroidContext(this);
    ref=new Firebase("https://texter10c.firebaseio.com");

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressDialog.setMessage("Logging in !");
            progressDialog.setTitle("Hang on!");
            progressDialog.show();

            ref.authWithPassword(emailField.getText().toString(), passwordField.getText().toString(), new Firebase.AuthResultHandler() {
                @Override
                public void onAuthenticated(AuthData authData) {
                    Log.e("Authenticated","Authenticated");
                    getUserIdandLogin();
                }

                @Override
                public void onAuthenticationError(FirebaseError firebaseError) {
                    progressDialog.dismiss();
                    Toast.makeText(LoginActivity.this, firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    });

    signupButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
            startActivity(intent);
        }
    });

    googleSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressDialog.setTitle("Contacting Google");
            progressDialog.setMessage("Logging you in");
            progressDialog.show();
            if(!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
        }
    });

}

private void getGoogleToken(){

    AsyncTask<Void,Void,String> task=new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            final String scopes="oauth2:"+"https://www.googleapis.com/auth/plus.login"+" "+"https://www.googleapis.com/auth/plus.me";
            try {
                if(!mGoogleApiClient.isConnected())
                {
                    mGoogleApiClient.connect();
                }
                googleAccessToken= GoogleAuthUtil.getToken(LoginActivity.this,Plus.AccountApi.getAccountName(mGoogleApiClient),scopes);
                Log.e("AccessToken",googleAccessToken+"");
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (GoogleAuthException e)
            {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                ref.authWithOAuthToken("google", googleAccessToken, new Firebase.AuthResultHandler() {
                    @Override
                    public void onAuthenticated(final AuthData authData) {
                        try {
                            Log.e("Firebase", "Google Authentication Success");
                            Log.e("Username", authData.getProviderData().get("displayName").toString());
                            Log.e("Id", authData.getProviderData().get("id").toString());


                            Firebase googleUserRef = ref.child("UserDetails/names/" + authData.getProviderData().get("id").toString());
                            Map<String, String> googleUserMap = new HashMap<String, String>();
                            googleUserMap.put("Username", authData.getProviderData().get("displayName").toString());
                            final String UserID = "GoogleUser" + authData.getProviderData().get("displayName") + authData.getProviderData().get("id");
                            googleUserMap.put("UserId", UserID);

                            googleUserRef.setValue(googleUserMap, new Firebase.CompletionListener() {
                                @Override
                                public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                                    progressDialog.dismiss();
                                    dataStore.setCurrentUserName(authData.getProviderData().get("displayName").toString());
                                    dataStore.setCurrentUserID(UserID);
                                    storeDatainSharedPreferences();
                                    Intent intent = new Intent(LoginActivity.this, DialogActivity.class);
                                    startActivity(intent);
                                }
                            });
                        }
                        catch (NullPointerException e)
                        {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onAuthenticationError(FirebaseError firebaseError) {
                        Log.e("GogoleAuthFailed", firebaseError.getMessage());

                    }
                });
            }
            catch (NullPointerException e)
            {
                Log.e("Accesstoken problem",e.getMessage());
            }
        }
    };
    task.execute();
}

public void getUserIdandLogin()
{
    dataStore.userDialogMap=new ArrayList<Map<String,String>>();
    dataStore.generatedChatIds=new ArrayList<>();
    Firebase refUser=ref.child("UserDetails/names");
    refUser.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Map<String, String> map = new HashMap<String, String>();
            map = dataSnapshot.getValue(Map.class);
            try{
                if (map.get("Email").equals(emailField.getText().toString()))
                {
                    Toast.makeText(LoginActivity.this, "Successfilly Logged in", Toast.LENGTH_SHORT).show();
                    dataStore.setCurrentUserName(map.get("Username"));
                    dataStore.setCurrentUserID(map.get("UserId"));
                    intent=new Intent(LoginActivity.this,DialogActivity.class);
                    startActivity(intent);
                    storeDatainSharedPreferences();
                    progressDialog.dismiss();
                }

            }
            catch (NullPointerException e)
            {
                Log.e("NullPointerGUser",e.getMessage());
            }
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
}

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();
    }
    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();
    }
}

private void removeDatainSharedPreferences() {
    SharedPreferences.Editor editor = getSharedPreferences(NEW_PREFS, MODE_PRIVATE).edit();
    editor.remove("CurrentUsername");
    editor.remove("CurrentUserId");
    editor.commit();
}


private void initialize() {
    emailInputLayout=(TextInputLayout)findViewById(R.id.emailInputLayout);
    emailField=(EditText)findViewById(R.id.emailField);
    passwordField=(EditText)findViewById(R.id.passwordField);
    passwordInputLayout=(TextInputLayout)findViewById(R.id.passwordInputLayout);
    loginButton=(Button)findViewById(R.id.loginButton);
    emailInputLayout.setHint("Email");
    passwordInputLayout.setHint("Password");
    progressDialog=new ProgressDialog(LoginActivity.this);
    signupButton=(TextView)findViewById(R.id.signupButton);
    forgotPasswordButton=(TextView)findViewById(R.id.forgotPasswordField);
    googleSignInButton=(SignInButton)findViewById(R.id.googleSignInButton);
    googleSignInButton.setColorScheme(SignInButton.COLOR_AUTO);
    forgotPasswordButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(LoginActivity.this,ForgotPasswordActivity.class);
            startActivity(intent);
        }
    });

    SharedPreferences sharePreferences=getSharedPreferences(NEW_PREFS,MODE_PRIVATE);
    if(!sharePreferences.getString("CurrentUsername","null").equals("null")) {
        Log.e("SharedPreferences", sharePreferences.getString("CurrentUsername", "null"));
        Log.e("SharedPreferences",sharePreferences.getString("CurrentUserId",null));
        Intent intent=new Intent(LoginActivity.this,DialogActivity.class);
        startActivity(intent);
    }

    mGoogleApiClient=new GoogleApiClient.Builder(this)
            .addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN)
            .addScope(Plus.SCOPE_PLUS_PROFILE)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();


   if(!isNetworkAvailable())
   {
      snackbar=Snackbar.make(findViewById(android.R.id.content),"You are offline",Snackbar.LENGTH_INDEFINITE)
              .setAction("Retry", new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      if(!isNetworkAvailable())
                          dismissSnackBar();
                      else
                          snackbar.show();
                  }

              });
       snackbar.show();
   }

}

private void dismissSnackBar() {
    snackbar.dismiss();
}


private boolean isNetworkAvailable()
{
    ConnectivityManager manager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkIngo=manager.getActiveNetworkInfo();
    return networkIngo!=null&& networkIngo.isConnected();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
        Log.e("GoogleApi","Connected");
        getGoogleToken();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e("GoogleApi",connectionResult.toString());
    if(!connectionResult.hasResolution())
    {
        GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(),LoginActivity.this,0).show();
    }
    if(connectionResult.isSuccess())
    {
        getGoogleToken();
    }
    try
    {
        connectionResult.startResolutionForResult(this,100);
    }
    catch (IntentSender.SendIntentException e)
    {
        e.printStackTrace();
    }
}

}

`

14 个答案:

答案 0 :(得分:9)

只需在获取数据后添加此singIn()方法

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

答案 1 :(得分:7)

您只需要清除预先登录的帐户。为此,将以下内容添加为signIn()函数下的第一行: mGoogleSignInClient.signOut();

 private void signIn() {
    // clearing previous signin caches
       mGoogleSignInClient.signOut();

    //getting the google signin intent
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    //starting the activity for result
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

答案 2 :(得分:6)

最简单的方法是在处理结果后注销客户端(onActivityResult)。在触发注销之前,只需确保客户端已连接。这是我的代码片段:

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);
        }
    }
}

答案 3 :(得分:1)

简单地为我锻炼

1&GT; Activity implements GoogleApiClient.OnConnectionFailedListener {

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

3&gt;在OnButtonClicked

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

4&GT;

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());
        }
    }

答案 4 :(得分:1)

那些在kotlin中需要它的人对我有用,我确实在发出新的登录请求之前清除了当前的登录缓存

[LightGBM] [Info] Total Bins 3499
[LightGBM] [Info] Number of data: 595192, number of used features: 25
/Users/Jame/anaconda3/lib/python3.6/site- 
packages/lightgbm/basic.py:725: UserWarning: categorical_feature in 
param dict is overridden.
warnings.warn('categorical_feature in param dict is overridden.')
[LightGBM] [Warning] Unknown parameter: vebose
[1] valid_0's multi_logloss: 2.35527
 Training until validation scores don't improve for 50 rounds.
[2] valid_0's multi_logloss: 2.31477
[3] valid_0's multi_logloss: 2.27614
[4] valid_0's multi_logloss: 2.23926
[5] valid_0's multi_logloss: 2.20397
[6] valid_0's multi_logloss: 2.16997
[7] valid_0's multi_logloss: 2.1372
[8] valid_0's multi_logloss: 2.10566
[9] valid_0's multi_logloss: 2.07528

您可以在此处查看完整的源代码:https://github.com/transcodium/TNSMoney-Android/blob/master/app/src/main/java/com/transcodium/tnsmoney/SocialLoginActivity.kt

答案 5 :(得分:0)

使用以下方式注销您的用户:

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

答案 6 :(得分:0)

我在使用javascript客户端搜索解决方案时发现了这个问题,但它可能与Android类似。

signIn({ prompt: 'select_account' })

  

<强> select_account

     

授权服务器会提示用户选择Google帐户。这允许拥有多个帐户的用户在多个帐户中选择他们可能拥有当前会话的帐户。

请参阅https://developers.google.com/identity/sign-in/web/reference#googleauthsigninoptions

答案 7 :(得分:0)

您不是通过注销来撤销用户,而是使用以下内容来实现您的需求:

将此代码放入任何活动中,然后在退出按钮中点击它:

ActivityCompat.OnRequestPermissionsResultCallback

}

WebElement ele1 = driver.findElement(By.id("dvfarecal")); ele1.click(); WebDriverWait wait = new WebDriverWait(driver, 5); WebElement ele2 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//img[@src='img/right.png']"))); ele2.click(); driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); WebElement date = driver.findElement(By.id("snd_3_10/05/2017")); date.click();

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

onCreate()

中覆盖此内容
mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();

参考链接:Google Developer Page

答案 8 :(得分:0)

您需要从google客户端注销用户

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

哪里

private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;

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

答案 9 :(得分:0)

我正在使用Firebase Auth UI,对我而言,此解决方法是;

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

登录后,然后;

AuthUI.signOut(context)

退出时

答案 10 :(得分:0)

这对我有用。 !!

  @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();

            }

如果要在Fragment或Activity中再次输入,则需要重新创建这些变量

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();

答案 11 :(得分:0)

成功登录后,只需添加mGoogleSignInClient.signOut();

private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        mAuth.signInWithCredential(credential).addOnCompleteListener(this, task -> {
            if(task.isSuccessful()) {
                mGoogleSignInClient.signOut();
                updateUI();
            } else {
                Toast.makeText(this, "Something went wrong.", Toast.LENGTH_SHORT).show();
            }
        });
    } catch (ApiException e) {
        Log.w("SignIn Failed", "signInResult:failed code=" + e.getStatusCode());
        updateUI(null);
    }
}

答案 12 :(得分:0)

对于 2K21 中的人来说,这是您需要做的,

const encryptedBase64Key = 'bXVzdEJlMTZCeXRlc0tleQ==';
const parsedBase64Key = enc.Base64.parse(encryptedBase64Key);

const encryptedCipherText = 'dItqis/6MoMJ4mKWDt2zVw==';
const decodeBase64Key = enc.Base64.parse(encryptedCipherText);

const decryptedData = AES.decrypt({
    cipherText: decodeBase64Key
    }, parsedBase64Key, {
        mode: mode.CBC,
        padding: pad.Pkcs7
})

答案 13 :(得分:-1)

如果您有任何注销功能。将以下代码放在注销代码之前:

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();
}

希望这会有所帮助。

  

编辑:您也可以尝试使用以下代码替换storeDatainSharedPreferences方法:

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();
}}
  

说明:For First解决方案:清除所有Cookie的代码   与您的申请相关。在您的情况下,这可以提供帮助   因为您想要清除以前可能存储的数据   饼干。

     

说明:对于第二个解决方案:这是断开mGoogleApiClient的代码。这将是有用的,因为您已将数据存储在sharedPref中,现在您不需要mGoogleApiClient