Firebase Facebook authentication showing weird activity - android

We are implementing Firebase Facebook authentication for one of our projects. We have followed the steps mentioned in the documentation as well.
Here is the oAuth URL:
https://<APP_NAME>.firebaseapp.com/__/auth/handler
I've added the rest of the credentials as well (i.e the APP_ID & APP_SECRET), moreover the app is in development stage and I've added the key hash as well to the Facebook portal and Firebase portal.
The Login initial flow works well, but when the user confirm the permission to grant access, the callback register doesn't respond at all, neither with negative nor positive acknowledgement.
Here's our piece of code:
private static final String TAG = "FacebookLogin";
private CallbackManager mCallbackManager;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError"+ error);
// ...
}
});
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(FacebookLoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
Please let us know if we missed anything. I'm assuming there's something wrong about the callback URL, thus a bit more information on the same would be helpful as Firebase documentation doesn't clearly state about how to build up that URL. Thanks in advance.

Did you add
mCallbackManager.onActivityResult(requestCode, resultCode, data);
in your onActivityResult block?
Edit
Referring to the sample from Firebase https://github.com/firebase/quickstart-android/blob/master/auth/app/src/minSdkJellybean/java/com/google/firebase/quickstart/auth/FacebookLoginActivity.java,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
If this is not added, there would be no callback.

Related

Authentication failed when doing Facebook login through firebase in android

I am developing an app in which i can give option to the user to login through facebook. Now, I am using firebase for this and I am getting authentication failed message whenever I try to login. It is going in the next activity but it is saying "Authentication failed" message.
Here is my code. This is my main activity:-
public class MainActivity extends AppCompatActivity {
private CallbackManager mCallbackManager;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView txtUser;
private TextView txtEmail;
private ImageView imgProfile;
private LoginButton logoutButton;
private LoginButton loginButton;
private static final String TAG = "MainActivity";
private FirebaseAuth mAuth;
PackageInfo info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser!=null){
updateUI(currentUser);
}
}
private void updateUI(FirebaseUser currentUser) {
Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_SHORT);
Intent intent = new Intent(MainActivity.this,AccountActivity.class);
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
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());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
}
Now, I have got my hash key using the following method:-
try {
PackageInfo info = getPackageManager().getPackageInfo(
getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT));
}
}
catch (PackageManager.NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}
And have put it in my fb developer console. It is still showing this error. Can please anybody explain what I am doing wrong here?
When I checked logcat, the message is shown here: -" An internal error has occurred. [ API key not valid. Please pass a valid API key".
I dont even know where this API key was used. Please help. Thanks
There was a step before signing in at firebase where you have to register your app at firebase console. I havent done that.
I made a new project, followed every step at firebase. And I am not getting any error now.

Firebase Authentication with Facebook login has failed while the Facebook account has logged on

To my knowledge, all Facebook and Firebase connections are linked and all code should be functional. However, the authentication still isn't passing through Firebase, even though it is being logged on from Facebook.
My Code: ActMain.java
public class ActMain extends AppCompatActivity {
private FirebaseAuth fAuth;
/* Facebook */
private CallbackManager mCallbackManager;
private static final String TAG = ActMain.class.getSimpleName();
/* onCreate */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_main);
// Initialize Firebase Auth
fAuth = FirebaseAuth.getInstance();
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
}
/* Facebook */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token)
{
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
fAuth.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 = fAuth.getCurrentUser();
updateUI(user);
}
else
{
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(ActMain.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
I am totally lost on where to continue as it had worked before. Could I possibly be doing something very minor but due to that causing the authentication to fail?
Get the hashkey of your current package and put it on fb developer console.Then this will work.
I had the same error but the problem was that I am trying to login with same email on facebook & google so the email should be unique for each user.

Android Firebase Facebook Authentication Logout function

I am using the facebook auth medthod with firebase and I can't figure out how to properly Log out a user. After I press the 'Continue with Facebook' button and give it access to my profile the button changes in 'Log out' and shows a dialog when I click it. The problem is that it doesn't actually log me out and the state is still signed in.
I found here how to log out the user from Firebase and Facebook in my app but I can't figure out where to put those 2 lines. I am looking for a Logout function or something like that.
I found here (different here) what might be my solution but it's pretty messy and can't understand. Can you please help me?
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.e(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "facebook:onError", error);
// ...
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
boolean userExists = false;
User userFirebase;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
userFirebase = mydata.getValue(User.class);
if(userFirebase.getEmail().equals(user.getEmail())){
Log.e(TAG, "User found in the database");
userExists = true;
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
break;
}
}
if (!userExists){
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").push().setValue(new User(user.getDisplayName(),user.getEmail(),0,0));
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); // checks if the user is in database and writes him if not
} else {
// User is signed out
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.e(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.e(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.e(TAG, "signInWithCredential", task.getException());
Toast.makeText(getBaseContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
You need to implement your own button and add and OnClickListener with the 2 methods mentioned :
Button logoutButton = (Button) findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
}
});
You can't use the facebook logout button , because it only logs you out of facebook and you need the firebase logout aswell.

Start an activity in firebase facebook authentication code

Why i can't startActivity in the facebook authentification code ?
1.The code is running well except that after the login i want to start an activity ,mean it should be somewhere to put the startActivity methode
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final String TAG = "Login";
private CallbackManager mCallbackManager;
Intent intent=new Intent(this,MainActivity.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
AppEventsLogger.activateApp(this);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
//startActivity(intent);
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
// ...
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
// ...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
// [START_EXCLUDE silent]
//showProgressDialog
// [END_EXCLUDE]
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
//hideProgressDialog();
// [END_EXCLUDE]
}
});
}
// [END auth_with_facebook]
}
You can do this in your AuthStateListener where currently you have:
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
// you can also add anything else that should happen when user
// has successfully signed in
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
As the comment states, when user != null the user is signed in, so that's where you can start your Activity or whatever you want to do.
When the user is successfully signed into Firebase Auth via Facebook (or any other logins you add) the onAuthStateChanged method will be called.

Facebook authentication in firebase not working

What I'm trying to do is login with Facebook using Firebase and then get name, email, profile picture and uid and then store it to Firebase Database.
Everything is working fine until clicking on login button and then the Facebook account window pop up. After that, when I select an account by clicking "Continue With Rishabh", nothing happens.
No authentication, no error, nothing. Same Facebook account selection window stays on screen and nothing happens.
Any help will be appreciated.
Here is my SignInActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
mSignInToolbar = (Toolbar) findViewById(R.id.signInToolbar);
setSupportActionBar(mSignInToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRef = FirebaseDatabase.getInstance().getReference().child("Users");
mRef.keepSynced(true);
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passowrdField);
mSigninBtn = (Button) findViewById(R.id.signinBtn);
mProgress = new ProgressDialog(this);
// Initialize Facebook Login button
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
mProgress.setMessage("Logging in...");
mProgress.show();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
DatabaseReference childRef = mRef.child(uid);
childRef.child("name").setValue(name);
childRef.child("email").setValue(email);
childRef.child("image").setValue(image);
mProgress.dismiss();
Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
});
}
See what all you need to do is to change some permission in facebook developer page. See the below picture make sure you too make required permission "Yes" as I did :
FacebookSdk.sdkInitialize(getApplicationContext());
Put this in the Application.
I've solved my problem by running the application in a real device (not in the emulator).

Categories

Resources