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

问题描述 投票:0回答:3

在facebook和firebase的官方网站上阅读了很多文档后,我在这里找不到明确的答案

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

  1. 在firebase中“保存和验证”用户的正确方法是什么 - 我的意思是在数据库中选择“子”键和值,或者使用facebook用户详细信息创建新的firebase用户?
  2. 登录后如何将当前用户的访问权限设置为他在数据库中的列表?
android facebook-graph-api firebase firebase-realtime-database firebase-authentication
3个回答
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
      });
  }

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) {

        }
    });

0
投票

在这里,我尝试解决与firebase身份验证的Facebook集成。

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

在build.gradle(应用程序级别)中添加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();

希望对你有帮助 :-)

© www.soinside.com 2019 - 2024. All rights reserved.