Android_Google登录和Facebook登录并使用Firebase身份验证

一、接入摘要

  • 时间:2021-04-15
  • 版本:google 19.0.0,facebook 9.0.0,firebase 20.0.4
  • 语言:java
  • 内容:google登录和facebook登录,firebase验证

firebase 这玩意可还行,google旗下产品,集成 Google、Facebook、Twitter、Github、Microsoft、Yahoo 等账号授权登录统一验证和管理账号。

二、接入流程

  1. google play 后台创建应用,配置应用信息,拿到参数 google-services.json
  2. facebook 后台创建应用,配置应用信息,拿到参数 app_id
  3. firebase 后台创建应用,关联 google 和 facebook
  4. 客户端代码接入

注:所有创建的应用包名签名要和客户端都一致,不要搞错了

三、客户端接入

集成依赖库

project 项目的 build.gradle 加入下面代码

dependencies {
     
    ...
    classpath 'com.google.gms:google-services:4.3.4'
    ...
}

module 的 build.gradle 加入下面代码

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

dependencies {
     
    ...
    //firebase
    implementation 'com.google.firebase:firebase-auth:20.0.4'
    //google
    implementation 'com.google.android.gms:play-services-auth:19.0.0'
    //facebook
    implementation 'com.facebook.android:facebook-login:9.0.0'
    ...
}

配置AndroidStudio项目

google

google-services.json 复制到以下路径:

  • project/module/src/debug/google-services.json
  • project/module/src/release/google-services.json

facebook

  • 打开您的 /module/src/main/res/values/strings.xml 文件
  • 添加如下代码:
<string name="facebook_app_id">{facebook AppId}string>
<string name="fb_login_protocol_scheme">fb{facebook AppId}string>
  • 打开 /module/src/main/AndroidManifest.xml 文件
  • application 节点下添加如下代码:
<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
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter><action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="@string/fb_login_protocol_scheme" />
    intent-filter>
activity>

代码接入

1、初始化 firebase

firebase集成是作为 google 和 facebook 登录的验证以及统一的账号管理,比单独使用 google 或facebook 账号验证和管理方便,开开发者需求

private FirebaseAuth mAuth;

/**
 * 初始化 FirebaseAuth 实例
 */
private void initFirebase() {
     
    mAuth = FirebaseAuth.getInstance();
}

2、google 登录

参考地址
firebase:https://firebase.google.com/docs/auth/android/google-signin?authuser=0
google官方:https://developers.google.com/identity/sign-in/android/sign-in?authuser=0

/**
 * google 登录
 */
private void googleLogin() {
     
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    // Build a GoogleSignInClient with the options specified by gso.
    GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, gso);

    //启动登录,在onActivityResult方法回调
    Intent signInIntent = googleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, 1001);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     
    super.onActivityResult(requestCode, resultCode, data);
    //google登录
    if (requestCode == 1001) {
     
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
     
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            if (account != null) {
     
                //firebase验证google登录
                firebaseAuthWithGoogle(account.getIdToken());
            }
        } catch (ApiException e) {
     
            // Google Sign In failed, update UI appropriately
        }
    }
}

3、验证 google 登录

如果开发者不用firebase,而是 google 官方的验证,可参考https://developers.google.com/identity/sign-in/android/backend-auth?authuser=0

/**
 * firebase 验证 google 登录
 *
 * @param idToken google 授权成功 token
 */
private void firebaseAuthWithGoogle(String idToken) {
     
    try {
     
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
     
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
     
                        if (task.isSuccessful()) {
     
                            //验证成功,请求我们服务端保存用户信息
                            FirebaseUser user = mAuth.getCurrentUser();
                            uploadServer(user);
                        }
                    }
                });
    } catch (Exception e) {
     
        e.printStackTrace();
    }

}

4、facebook 登录

参考地址
firebase:https://firebase.google.com/docs/auth/android/facebook-login?authuser=0
facebook 官方:https://developers.facebook.com/docs/facebook-login/android

private CallbackManager fbCallbackManager;

private void facebookLogin() {
     
    fbCallbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile"));
    LoginManager.getInstance().registerCallback(fbCallbackManager, new FacebookCallback<LoginResult>() {
     
        @Override
        public void onSuccess(LoginResult loginResult) {
     
            //facebook授权成功,去firebase验证
            if (loginResult != null) {
     
                AccessToken accessToken = loginResult.getAccessToken();
                if (accessToken != null) {
     
                    String token = accessToken.getToken();
                    firebaseAuthWithFacebook(token);
                }
            }
        }

        @Override
        public void onCancel() {
     
            //取消授权
        }

        @Override
        public void onError(FacebookException error) {
     
            //授权失败
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     
    super.onActivityResult(requestCode, resultCode, data);
    //fb登录
    if (fbCallbackManager != null) {
     
        fbCallbackManager.onActivityResult(requestCode, resultCode, data);
    }
    ...
}

5、验证 facebook 登录

private void firebaseAuthWithFacebook(String token) {
     
    AuthCredential credential = FacebookAuthProvider.getCredential(token);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
     
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
     
//                        SGameLog.e(TAG, "google channel signInWithCredential:task");
                    if (task.isSuccessful()) {
     
                        // Sign in success, update UI with the signed-in user's information
                        FirebaseUser user = mAuth.getCurrentUser();
                    } else {
     
                        //验证失败另作处理
                    }
                }
            });
}

6、上传服务端

/**
 * 上传用户信息到服务端
 *
 * @param user firebase用户信息
 */
private void uploadServer(FirebaseUser user) {
     
    if (user != null) {
     
        String uid = user.getUid();
        String displayName = user.getDisplayName();
        String email = user.getEmail();
        //上传服务端
    }
}

7、自动登录

如需要自动自动可接入,在授权登录成功后,本地会在一定期限内保存用户信息
登录前检查登录状态:

/**
 * 检查登录状态
 */
private void checkFirebaseUserAuth() {
     
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser != null) {
     
        String displayName = currentUser.getDisplayName();
        String email = currentUser.getEmail();
        String uid = currentUser.getUid();
        // 如果过查到用户信息说明已经登录过而且没过期或者没有登出
        // 直接上传服务端,登录成功
        uploadServer(currentUser);
    }
}

8、登出(注销)

如需主动登当前账号,调用如下代码:

FirebaseAuth.getInstance().signOut();

常见错误

  • google 登录错误码12500
    在 firebase 后台项目配置支持电子邮箱
    https://console.firebase.google.com/

  • firebase 验证报错:failure An internal error has occurred. [ CONFIGURATION_NOT_FOUND ],这个问题要检查一下 firebase 是否跟 google playfacebook 项目关联

四、收工

你可能感兴趣的:(Android开发,手游SDK,Android,谷歌登录,facebook登录,google,fb登录,firebase,google,登录)