Firebase autenthication在Android应用

时间:2017-02-07 13:48:38

标签: android firebase firebase-authentication facebook-login

我正在编写一个应该连接到firebase数据库的应用程序。一切正常,除了当我检查autenthication键(使用getAuth()方法)时,它总是返回null。我在我的应用程序中使用facebook进行了autenthication,我想在我的数据库上启用autenthication:

{
  "rules": {
        ".read": "auth != null",
            ".write":"auth != null"
  }
}

我的项目有2个类,一个是LoginActivity,允许用户使用Facebook帐户在数据库中创建帐户:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    firebaseAutenthication = FirebaseAuth.getInstance();

    //Get current user ID
    FirebaseUser mUser = firebaseAutenthication.getCurrentUser();
    if (mUser != null) {
        // Club is signed in
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        String uid = firebaseAutenthication.getCurrentUser().getUid();
        String image = firebaseAutenthication.getCurrentUser().getPhotoUrl().toString();
        intent.putExtra("user_id", uid);
        if (image != null || !Objects.equals(image, "")) {
            intent.putExtra("profile_picture", image);
        }
        startActivity(intent);
        finish();
        Log.e(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
    }

    //Setup firebase autenthication listener
    firebaseAutenthicatorListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser mUser = firebaseAuth.getCurrentUser();
            if (mUser != null) {
                // Club is signed in
                Log.e(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
            } else {
                // Club is signed out
                Log.e(TAG, "onAuthStateChanged:signed_out");
            }

        }
    };

    //Initialize facebook SDK
    FacebookSdk.sdkInitialize(getApplicationContext());
    if (BuildConfig.DEBUG) {
        FacebookSdk.setIsDebugEnabled(true);
        FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    }

    //Create callback manager for facebook login
    //onSucces calls login method
    //TODO: onCancel and OnError should display popup with information that login failed
    callbackManagerFromFacebook = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(callbackManagerFromFacebook, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.e(TAG, "facebook:onSuccess:" + loginResult);
            signInWithFacebook(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            Log.e(TAG, "facebook:onCancel");
        }

        @Override
        public void onError(FacebookException error) {
            Log.e(TAG, "facebook:onError", error);
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    firebaseAutenthication.addAuthStateListener(firebaseAutenthicatorListener);
}

@Override
public void onStop() {
    super.onStop();
    if (firebaseAutenthicatorListener != null) {
        firebaseAutenthication.removeAuthStateListener(firebaseAutenthicatorListener);
    }
}

//FaceBook
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManagerFromFacebook.onActivityResult(requestCode, resultCode, data);
}

private void signInWithFacebook(AccessToken token) {
    Log.e(TAG, "signInWithFacebook:" + token);

    showProgressDialog();


    credential = FacebookAuthProvider.getCredential(token.getToken());
    firebaseAutenthication.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(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        String uid = task.getResult().getUser().getUid();
                        String name = task.getResult().getUser().getDisplayName();
                        String email = task.getResult().getUser().getEmail();
                        Uri imageUri = task.getResult().getUser().getPhotoUrl();
                        String image = "";
                        if(imageUri != null) {
                            image = imageUri.toString();
                        }

                        //Create a new User and Save it in Firebase database
                        User user = new User(uid, name, null, email, null, null, "About Me");
                        firebaseUsers.child(uid).setValue(user);

                        //Start MainActivity and pass user data to it
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        intent.putExtra("user_id", uid);
                        intent.putExtra("profile_picture", image);
                        startActivity(intent);
                        finish();
                    }

                }
            });

第二个是MainActivity,应该从他的Facebook个人资料中获取用户信息并将其放入数据库中:

void getValueFromFirebase() {
    Log.e(TAG, "Started getValueFromFirebase()");



    firebase.child(userID).child("name").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String data = dataSnapshot.toString();
            Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Toast.makeText(getApplicationContext(), firebaseError.toString(), Toast.LENGTH_LONG).show();
        }
    });



}

void createFirebaseConnection() {
    this.firebase = new Firebase(AppConstants.FIREBASE_URL_USERS);
    this.firebaseAuthentication = FirebaseAuth.getInstance();
    this.firebaseUser = firebaseAuthentication.getCurrentUser();

    //Create listener for firebase autenthication
    //Log if user is disconnected
    this.firebaseAutenthicationStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.e(TAG, "onAuthStateChanged:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged: user is not signed in!");
            }
        }
    };
    firebaseAuthentication.addAuthStateListener(this.firebaseAutenthicationStateListener);

    //Check if auth is done
    //If not, autenthicate with Facebook Token
    if(this.firebase.getAuth() == null) {
        Log.e(TAG, "firebase.getAuth() == null, starting authWithFacebook()...");
        authWithFacebook();
    }
}

void authWithFacebook() {
    Log.e(TAG, "authWithFacebook() started!");

    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    Log.e(TAG, "Facebook Token: " + accessToken.getToken());

    Log.e(TAG, "Auth: " + firebase.getAuth());

}

 void readDataFromLoginActivity() {
    //Get the uid for the currently logged in Club from intent data passed to this activity
    this.userID = getIntent().getExtras().getString("user_id");
    //Get the imageUrl  for the currently logged in Club from intent data passed to this activity
    //Load image to ImageView
    this.userImageUrl = getIntent().getExtras().getString("profile_picture");
}

@Override
public void onBackPressed() {
    if (userProfile.moveState == 1) {
        userProfile.slideBottom();
    } else {
        super.onBackPressed();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG, "onCreate() called...");
    setContentView(R.layout.activity_main);
    lay = (RelativeLayout) findViewById(R.id.lay);
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;
    Log.e(TAG, "readDataFromLoginActivity() called...");
    readDataFromLoginActivity();


    Log.e(TAG, "createFirebaseConnection() called...");
    createFirebaseConnection();


}

@Override
protected void onStart() {
    super.onStart();
    Log.e(TAG, "onStart() called...");
    addTopTabBar();
    addProfileFragment();
    addLeftSideBar();
    Log.e(TAG, "Binding UI Elements...");
    bindUIElements();

    getValueFromFirebase();

}

然而,我显示的吐司总是显示&#34;权限错误&#34;。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您在同一个应用中使用旧版2.x.x SDK和新的10.x.x SDK。这不是好的做法,可能是问题的根源。从依赖项中删除此行,并进行所需的代码更改,以仅使用新SDK的功能。

compile 'com.firebase:firebase-client-android:2.x.x'

新SDK的软件包名称以com.google.firebase开头。旧版SDK的那些以com.firebase.client开头。

有用的提示在Upgrade Guide