firebase-authentication Google Plus登录身份验证
示例
使用Plus登录验证用户
onCreate
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestScopes(new Scope(Scopes.PLUS_LOGIN)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Auth.GOOGLE_SIGN_IN_API,gso) .addApi(Plus.API) .build();
onStart()
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
mAuth.addAuthStateListener(mAuthListener);
}
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
getProfileInformation();
//getGoogleOAuthTokenAndLogin();
Toast.makeText(this, "User is connected! (in onConnected MActivty)",Toast.LENGTH_LONG).show();
//获取用户信息
//登录后更新用户界面
//updateUI(true);
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
//updateUI(false);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this,
0).show();
} else if(connectionResult.hasResolution()) {
mConnectionResult = connectionResult;
resolveSignInError();
}
}
private void resolveSignInError() {
Log.e("pavan", "User RESOLVE SIGN IN ERROR CALLED OUT OF IF");
if(mSignInClicked){
if (mConnectionResult.hasResolution()) {
try {
Log.e("pavan", "User RESOLVE SIGN IN ERROR CALLED OUT OF IF TRY");
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, GOOGLE_SIGIN);
} catch (IntentSender.SendIntentException e) {
Log.e("pavan", "User RESOLVE SIGN IN ERROR CALLED OUT OF IF CATCH");
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}获取资料信息
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
} catch (Exception e) {
e.printStackTrace();
}
}使用Firebase进行身份验证,
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
//AuthCredential凭据=GoogleAuthProvider.getCredential(tokenCredential,null);
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TAG", "signInWithCredential:onComplete:" + task.isSuccessful());
//如果登录失败,则向用户显示一条消息。如果登录成功
//将会通知auth状态监听器,并处理逻辑
//登录的用户可以在侦听器中处理。
if (!task.isSuccessful()) {
Log.w("TAG", "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "验证失败。",
Toast.LENGTH_SHORT).show();
}else{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.e("SahajLOG", "登录PREFISSSSSSSSONACTIVITYRESULT "+prefs.getBoolean("AuthByGplus", AuthByGplus));
prefs.edit().putBoolean("AuthByGplus", true).commit();
Log.e("SahajLOG", "登录PREFISSSSSSSSONACTIVITYRESULT IFTRUE.. "+prefs.getBoolean("AuthByGplus", AuthByGplus));
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
//[START_EXCLUDE]
//hideProgressDialog();
//[END_EXCLUDE]
}
});
}onActivityResult
@Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == GOOGLE_SIGIN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
if (mGoogleApiClient.isConnected()) {
//getGoogleOAuthTokenAndLogin();
}
}
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(intent);
if (result.isSuccess()) {
//Google登录成功,已通过Firebase进行身份验证
GoogleSignInAccount account = result.getSignInAccount();
Log.e("SahajLOG", "account " + account.getIdToken());
//getGoogleOAuthTokenAndLogin();
firebaseAuthWithGoogle(account);
} else {
//Google登录失败,请适当更新用户界面
//[START_EXCLUDE]
Log.e("SahajLOG", "SIGN IN FAILED");
//[END_EXCLUDE]
}
}
public void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, GOOGLE_SIGIN);
}
}登出
@Override
public void onLogout() {
mAuth.signOut();
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
SignedInWithGoogle=false;
}
//Google登出
switchToLoginFragment();
}