在firebase facebook登录

时间:2017-11-13 13:46:01

标签: java android facebook firebase firebase-authentication

我正在开发firebase演示应用程序,其中我添加了firebase facebook以及google登录,所以google工作正常但是每当我尝试使用facebook登录时它会在运行时抛出Authentication failed所以我会尝试所有stackOverflow解决方案,但它没有工作,所以任何人都知道如何解决这个问题?

以下是我的登录代码: -

public class SplashScreen extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    //constant values
    public static final String USER_NAME="com.gaurav.javascripttutorial.username";
    public static final String USER_IMAGE="com.gaurav.javascripttutorial.userimage";
    public static final String USER_ID="com.gaurav.javascripttutorial.userid";

    int RC_SIGN_IN = 1000;

    //Firebase
    FirebaseAuth mAuth;
    GoogleApiClient mGoogleApiClient;
    CallbackManager mCallbackManager;

    //views
    private SignInButton googleLogin;
    private LoginButton facebookLogin;
    private ProgressDialog dialog;

    //Shared Preference
    SharedPreferences pref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.setApplicationId(getString(R.string.fb_app_id));
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.main_splashscreen);
        googleLogin = (SignInButton) findViewById(R.id.googleLogin);
        facebookLogin = (LoginButton) findViewById(R.id.facebookLogin);

        pref = this.getSharedPreferences("user",0);
        editor = pref.edit();

        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading, Please wait....");

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

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

        //Facebook configuration
        mCallbackManager = CallbackManager.Factory.create();

        mAuth = FirebaseAuth.getInstance();

        if (mAuth.getCurrentUser()!= null){
            FirebaseUser user = mAuth.getCurrentUser();
            editor.clear();
            editor.putString(USER_NAME,user.getDisplayName());
            editor.putString(USER_ID, user.getUid());
            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
            editor.commit();
            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        googleLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                googleSignIn();
            }
        });
        facebookLogin.setReadPermissions("email","public_profile");
        facebookLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                handleFacebookAccessToken(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                Toast.makeText(SplashScreen.this, "Facebook login cancel.", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(SplashScreen.this, "Something went wrong! Please try again", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void googleSignIn(){
        Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(intent,RC_SIGN_IN);
    }

    private void handleFacebookAccessToken(AccessToken token){
        final 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
                            FirebaseUser user = mAuth.getCurrentUser();
                            editor.clear();
                            editor.putString(USER_NAME,user.getDisplayName());
                            editor.putString(USER_ID, user.getUid());
                            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
                            editor.commit();
                            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(SplashScreen.this, "Authentication failed.", Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount account){
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){
                            FirebaseUser user = mAuth.getCurrentUser();
                            editor.clear();
                            editor.putString(USER_NAME,user.getDisplayName());
                            editor.putString(USER_ID, user.getUid());
                            editor.putString(USER_IMAGE, user.getPhotoUrl().toString());
                            editor.commit();
                            Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            dialog.dismiss();
                        }else {
                            Toast.makeText(SplashScreen.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN){
            if (resultCode == RESULT_OK) {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                dialog.show();
                if (result.isSuccess()) {
                    GoogleSignInAccount account = result.getSignInAccount();
                    firebaseAuthWithGoogle(account);

                } else {
                    Log.d("Status", String.valueOf(result.getStatus().getStatusCode()));
                    Toast.makeText(this, "SignIn failed", Toast.LENGTH_SHORT).show();
                }
            }else {
                Toast.makeText(this, "Result Code error", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_LONG).show();

    }
}

1 个答案:

答案 0 :(得分:0)

假设你已经正确配置了所有内容(否则,read the docs),这对我来说很好(Kotlin代码,对不起。如果你需要Java,只需进行翻译):

我的Activity扩展了AppCompatActivity

class ActivityLogin : AppCompatActivity() {

    private val callbackManager: CallbackManager = CallbackManager.Factory.create()
    private val mAuth: FirebaseAuth = FirebaseAuth.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_splashscreen)

        loginButton.setReadPermissions("email", "public_profile")
        loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(result: LoginResult) {
                handleFacebookAccessToken(result.accessToken)
            }

            override fun onCancel() {
                Toast.makeText(this@ActivityLogin, "Facebook Authentication canceled.", Toast.LENGTH_SHORT).show()
            }

            override fun onError(error: FacebookException?) {
                Toast.makeText(this@ActivityLogin, "Facebook Authentication failed.", Toast.LENGTH_SHORT).show()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleFacebookAccessToken(token: AccessToken) {
        val credential = FacebookAuthProvider.getCredential(token.token)
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        val mainIntent = Intent(this@ActivityLogin, ActivityFeed::class.java)
                        startActivity(mainIntent)
                        finish()
                    } else {
                        Toast.makeText(this@ActivityLogin, "Firebase Authentication failed.", Toast.LENGTH_SHORT).show()
                    }
                }
    }
}

如您所见,无需致电

FacebookSdk.setApplicationId(getString(R.string.fb_app_id));
FacebookSdk.sdkInitialize(getApplicationContext());

在您的活动期间onCreate()