一、接入摘要
- 時間: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 等賬號授權登錄統一驗證和管理賬號,
二、接入流程
- google play 后臺創建應用,配置應用資訊,拿到引數
google-services.json - facebook 后臺創建應用,配置應用資訊,拿到引數
app_id - firebase 后臺創建應用,關聯 google 和 facebook
- 客戶端代碼接入
注:所有創建的應用包名簽名要和客戶端都一致,不要搞錯了
三、客戶端接入
集成依賴庫
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-services.json 復制到以下路徑:
- project/module/src/debug/
google-services.json - project/module/src/release/
google-services.json
- 打開您的
/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 play和facebook專案關聯
四、收工
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/281299.html
標籤:其他
下一篇:兩年Android面試大廠上岸經
