问题
I'm trying to login from Facebook and Google API, the Google API works fine, the problem arises with Facebook login, everything is setup on the Facebook developers console and my app is live as well.
The problem is whenever user clicks on the login button (which is a customized ImageButton) the ProgressBar shows up and then it goes away and the app is still on the same activity without user being logged in.
The complete code for that activity is:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
progressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
Auth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
GoogleSignInOptions gso = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Google = (ImageView) findViewById(R.id.googleSignin);
Google.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SIGN_IN_REQUEST = 1;
signIn();
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
callbackManager = CallbackManager.Factory.create();
Facebook = (ImageView) findViewById(R.id.facebookSignin);
Facebook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SIGN_IN_REQUEST = 2;
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading...");
LoginManager.getInstance().logInWithReadPermissions(opening.this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG2, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
setFbData(loginResult);
progressDialog.dismiss();
}
@Override
public void onCancel() {
Log.d(TAG2, "facebook:onCancel");
Toast.makeText(getApplicationContext(),"facebook:oncancel",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
@Override
public void onError(FacebookException error) {
Log.d(TAG2, "facebook:onError", error);
Toast.makeText(getApplicationContext(),"facebook:onError",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
});
Email = (ImageView)findViewById(R.id.emailLogin);
Email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SignIn.class);
startActivity(intent);
finish();
}
});
AlreadyLoggedin = (ImageView)findViewById(R.id.Already);
AlreadyLoggedin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), login.class);
startActivity(intent);
finish();
}
});
}
private void signIn(){
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (SIGN_IN_REQUEST == 1) {
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(getApplicationContext(), "Google sign in Failed", Toast.LENGTH_LONG).show();
String s1 = task.getException().getMessage();
Toast.makeText(getApplicationContext(),"" + s1,Toast.LENGTH_LONG).show();
progressDialog.dismiss();
String s = task.getException().getMessage();
Toast.makeText(getApplicationContext(),"ErrorCode: " + s,Toast.LENGTH_LONG).show();
}
}
} else if (SIGN_IN_REQUEST == 2){
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Snackbar.make(findViewById(R.id.snake), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
progressDialog.dismiss();
updateUI(null);
}
// ...
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void updateUI(FirebaseUser user) {
/*
Intent intent = new Intent(opening.this, MainActivity.class);
startActivity(intent);
finish();
*/
progressDialog.dismiss();
if (SIGN_IN_REQUEST == 1) {
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
String uid = mAuth.getCurrentUser().getUid();
Intent intent = new Intent(opening.this, userInf.class);
intent.putExtra("UID", uid);
intent.putExtra("Phone", PhoneNumber);
intent.putExtra("Name", personName);
startActivity(intent);
finish();
}
} else if (SIGN_IN_REQUEST == 2) {
if (user != null) {
progressDialog.dismiss();
Intent intent = new Intent(opening.this, userInf.class);
intent.putExtra("Phone", PhoneNumber);
intent.putExtra("Name", Name);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(),"updating error",Toast.LENGTH_LONG).show();
}
}
}
private void setFbData(final LoginResult loginResult){
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = response.getJSONObject().getString("first_name");
String last_name = response.getJSONObject().getString("last_name");
Name = String.valueOf(first_name + " " + last_name);
} catch (JSONException e){
e.printStackTrace();
}
}
});
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
Toast.makeText(getApplicationContext(),"HandelingRequest",Toast.LENGTH_LONG).show();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
Auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
progressDialog.dismiss();
updateUI(user);
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(opening.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
updateUI(null);
}
}
});
}}
The log out is something like this:
D/FACELOG: facebook:onSuccess:com.facebook.login.LoginResult@d573369
D/GoogleActivity: handleFacebookAccessToken:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[public_profile, email]}
W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@6703527
I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
[FirebaseAuth:] Preparing to create service connection to gms implementation
I've been looking around for this from quite some time and have not found anything which solves my problem.
回答1:
I am using the following method for fb login, As per our knolwedge, we have tested all the boundary conditions & its working fine for us now and never faced any challenge yet.
//on click of fb button
private void handleFBLogin() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
LoginManager.getInstance().logOut();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
LoginManager.getInstance().logInWithReadPermissions(ActivityLogin.this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setFacebookData(loginResult, d);
}
});
}
@Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Canceled login ", Toast.LENGTH_SHORT); toast.show();
}
@Override
public void onError(FacebookException exception) {
d.dismiss();
if (exception instanceof FacebookAuthorizationException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
handleFBLogin();
return;
}
}
Toast.makeText(getApplicationContext(), "ERROR " + exception.toString(), Toast.LENGTH_SHORT); toast.show();
PackageInfo info;
try {
info = getPackageManager().getPackageInfo([your package name], PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (Exception e1) {
Log.e("name not found", e1.toString());
}
}
});
}
private void setFacebookData(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
final String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String id = response.getJSONObject().getString("id");
String email = null;
if (response.getJSONObject().has("email"))
email = response.getJSONObject().getString("email");
//put your code here
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
回答2:
from this link it is clear that the access token cannot be see in logcat. thats why you are seeing token:ACCESS_TOKEN_REMOVED
回答3:
the reason is, that you are mixing up Auth
and mAuth
in method handleFacebookAccessToken(AccessToken token)
.
the problem already introduces itself onCreate()
:
mAuth = FirebaseAuth.getInstance();
Auth = FirebaseAuth.getInstance();
remove Auth
and use the instance called mAuth
everywhere.
回答4:
Try calling intent in onSuccess()
method
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG2, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
setFbData(loginResult);
progressDialog.dismiss();
//call activity here
startActivity(new Intent(MainActivity.class));
}
回答5:
In the debug mode you have to enable the logging for access token. So Add this lines
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
}
LoginManager.getInstance().registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
final GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
if (object.has("id")) {
handleSignInResultFacebook(object); // Parse the json object for user details
} else {
Logger.e("FBLOGIN_FAILD", String.valueOf(object));
}
} catch (Exception e) {
e.printStackTrace();
dismissDialogLogin();
}
}
});
final Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,id,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
Logger.e("FBLOGIN_FAILD", "Cancel");
}
@Override
public void onError(FacebookException error) {
Logger.e("FBLOGIN_FAILD", "ERROR", error);
}
});
来源:https://stackoverflow.com/questions/52912641/sign-in-issue-using-facebook-authentication