Android应用程序 - 使用facebook登录firebase auth

时间:2016-06-08 12:39:17

标签: android facebook-graph-api firebase firebase-realtime-database firebase-authentication

在facebook和firebase的官方网站上阅读了很多文档 我没有找到明确的答案

我的应用设计: 第一次登录Facebook和电子邮件 第二个屏幕 - 用户可以添加和删除文本的列表(如Todo列表)。

  1. 在firebase中“保存并授权”用户的正确方法 - 我的意思是选项 在数据库中,如“子”键和值,或用facebook用户详细信息创建新的firebase用户?

  2. 登录后如何将当前用户的访问权限设置为数据库中的列表?

3 个答案:

答案 0 :(得分:1)

使用Ionic 2和Firebase 3

  import { Facebook } from 'ionic-native';
  import * as firebase from 'firebase';

  login() {
      Facebook.login(['public_profile', 'email']).then((data) => {
          //user logged in with Facebook successfully;

          // create credential object using facebook access token
          let credential = (<any> firebase.auth.FacebookAuthProvider).credential(data.authResponse.accessToken);

          // try to authenticate firebase
          firebase.auth().signInWithCredential(credential)
          .then(function(user) {
              // user logged into firebase successfully
          })
          .catch(function(error) {
          })
      }, (error) => {
        // something went wrong
      });
  }

答案 1 :(得分:0)

这里我在android中附加了一个示例facebook回调,其中包括带有firebase的facebook身份验证。

    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Firebase ref = new Firebase(AppConstants.FIREBASE_URL);//your firebase url
            AccessToken token = loginResult.getAccessToken();
            final ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
            dialog.setMessage("Logging....");
            dialog.show();
            Log.d("fbaccess", "Facebook AccessToken " + token.getToken());
            ref.authWithOAuthToken("facebook", token.getToken(), new Firebase.AuthResultHandler() {
                @Override
                public void onAuthenticated(AuthData authData) {
                    Log.d("FBLOGIN", "The Facebook user is now authenticated with your Firebase app");
                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(),"The Facebook user is now authenticated with your Firebase app",Toast.LENGTH_LONG).show();
                    //add your intent

                }

                @Override
                public void onAuthenticationError(FirebaseError firebaseError) {
                    // there was an error
                    Log.d("FBLOGIN", "Tthere was an error with your Firebase app");
                }
            });
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    });

答案 2 :(得分:0)

在这里,我尝试使用firebase身份验证解决facebook集成问题。

首先,您需要在Facebook开发人员中创建项目并获取facebook密钥,并在firebase控制台中创建项目并获取 google-services.json 文件并放入 app 项目结构。

在build.gradle(app level)中为facebook sdk和firebase身份验证添加依赖项。

  compile 'com.facebook.android:facebook-android-sdk:4.+'
  compile 'com.google.firebase:firebase-auth:11.6.2'
  compile 'com.google.android.gms:play-services-auth:11.6.2'

apply plugin: 'com.google.gms.google-services'

现在在build.gradle(proj level)中添加google play服务。

classpath 'com.google.gms:google-services:3.1.0'

在AndroidManifest.xml中添加facebook密钥

<uses-permission android:name="android.permission.INTERNET" />

<meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>


        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

<强> activity_login.xml

 <Button
      android:id="@+id/btnSignInFaceBook"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

<强> LoginActivity.class

public class LoginActivity extends AppCompactActivity{

 Button faceBookBtn;
 String fbId = "",fbemail="";
 private FirebaseAuth mAuth;
//Facebook Declaration
 CallbackManager callbackManager;
 LoginManager loginManager;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        initUI();
      }

      private void initUI(){
          faceBookBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                faceBookLogin();
            }
        });
      }
      private void faceBookLogin() {
        loginManager = LoginManager.getInstance();
        loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(final LoginResult loginResult) {
                Log.d(TAG, "facebook:onSuccess:" + loginResult);
                if (AccessToken.getCurrentAccessToken() != null) {

                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {

                                    if (object != null) {
                                        try {
                                            AppEventsLogger logger = AppEventsLogger.newLogger(LoginActivity.this);
                                            logger.logEvent("Facebook login suceess");

            handleFacebookAccessToken(loginResult.getAccessToken());

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,email,gender, birthday, about");
                    request.setParameters(parameters);
                    request.executeAsync();
                }
            }

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

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
            }
        });
        loginManager.logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "public_profile"));
    }
    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + token);
        mAuth = FirebaseAuth.getInstance();

        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();
                            if (user != null) {
                                Log.i(TAG, "email" + user.getEmail());
                            }

                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                        }


                    }
                });
    }

}

退出。

 FirebaseAuth.getInstance().signOut();

希望这会对你有所帮助: - )