Hello~今天來寫一點關於Firebase中的登入機制

在現代很多的網站中,我們都可以看見很多網站若有登入機制,都可以看見所謂的「第三方登入」

例如「以Google登入」、「以Facebook登入」

甚至中國的App還有「以支付寶登入」、「以微信登入」等等的登入方式

 

這種登入方式,通常就是為了省時間,加快使用者加入會員所設置的

一方對方網站可以不用還要你填寫一堆有的沒有的資料,二來也可以更快地提供服務,可謂是非常方便

那今天的實作,我就是要使用這一個登入機制來獲取登入者的資訊

來,上功能!

 

Github...這次沒有,程式是很簡單的,但是設定很麻煩...(嘆)

來吧!

 


 

1. 創建Firebase專案&載入相關函式庫

 

其實我之前在這裡也有寫過跟Firebase相關操作的文章,在這裏

->碼農日常-『Android studio』FCM雲端推播與通知系統(上)-建立第一個基本推播通知APP

整體來說,操作上是差不多的,不過就是用了不一樣的功能而已,就是這麼簡單

...雖然是這樣想,但實際上在運作的時候還是遇上了很多麻煩QQ

 

好啦,既然我會寫這篇文章,表示我也是處理完了各種麻煩後才寫的

那麽總之~我們來實作吧!

首先,打開好了你的專案後,點擊Tools->Firebase然後會看到以下畫面(編輯器右側),然後找到Auth.....Google Sign-In

截圖 2021-10-11 上午12.39.43

 

接著就到這一畫面

截圖 2021-10-11 上午12.40.37

首先點選1後,會開啟Firebase創建專案畫面,這時候點選新增專案即可

截圖 2021-10-11 下午12.18.24

接下來Google都會幫你填好專案名稱之類的,不用有什麼修改

Google Analytics就看人,你需要就用,我這個範例不需要

截圖 2021-09-04 下午12.35.31

OK,然後他就會開始創建,最後看到這個畫面就是完成囉!

再來點擊2,編輯器會自動幫你載入需要的函式庫

截圖 2021-10-11 上午12.40.37

基本上載入完後,就會看到這個畫面,就算完成囉!

截圖 2021-10-11 下午12.38.36

 

那如果你是有看過我之前寫的關於FCM操作的朋友可能會很納悶

「誒?為什麼上次的操作那麼複雜,這次的卻那麼簡單?」

呃,主要是因為在那篇中我所描述的這些操作都是手動來做的,而這次我就偷懶,直接讓程式自動處理了XD

 

OK,這時候可以去檢查一下你的build.gradle的兩個項目,來檢查一下函式庫有沒有都被確實載入

 

截圖 2021-10-11 下午12.43.17

build.gradle (Project)

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"
        classpath 'com.google.gms:google-services:4.3.10'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

 

build.gradle (Module)

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.noahliu.googlesigninexample"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.android.gms:play-services-auth:19.2.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

 


 

2. 設置SHA-1指紋與相關SDK設置

 

OK, 設置完成後,接下來就是比較麻煩的部分

首先,我們要在Firebase專案項目中開啟能被Google所登入的設置

請在專案項目點Authentication,然後點擊開始

截圖 2021-10-11 下午2.32.36

點選Sign-in method 再點Google

截圖 2021-10-11 下午2.34.24

接著,啟用他

截圖 2021-10-11 下午2.36.26

 

然後按下保存之後會看看到這個畫面

截圖 2021-10-11 下午2.38.00

這時候滑鼠移到上方,會在右側有一支筆的圖樣

截圖 2021-10-11 下午2.39.05

這時候再進去,就會看到他已經幫你把所有的資訊填入囉

截圖 2021-10-11 下午2.40.09

先記得這個頁面,這很重要

再來我們要來載入SDK~

這時候我們先來檢查一下你的專案中有沒有被載入了google-services.json這隻檔案

請先在左側的專案資料夾內,切換到Project檢視的模式

截圖 2021-10-11 下午1.00.36

 

然後理論上,你可以在src資料夾底下找到google-services.json這隻檔案

截圖 2021-10-11 下午1.01.04

如果沒有的話,請去項目設置中找到..

不過這時候如果你是沒有的也沒關係,因為等等我們也需要重新操作這一步驟

截圖 2021-10-11 下午1.02.40

 

好,注意了;到這邊雖然你程式是能寫的,也能執行

但是一但操作下去他的回應是會出錯的,那會錯的原因是在於Google那邊需要登記你的SHA-1 key

因此,我在這裡需要操作添加SHA-1 key

 

首先,回到編輯器

然後點擊Terminal,輸入以下指令(Mac版

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

截圖 2021-10-11 下午1.10.25

 

然後他會回你這一串

截圖 2021-10-11 下午1.11.53

然後複製起來MD5的那一串

再來,來到項目設置

截圖 2021-10-11 下午1.02.40

拉到最底下,看到這個畫面

請注意,目前SHA-1的部分是空白的

截圖 2021-10-11 下午1.19.16

點選「添加指紋」,輸入剛剛複製的那一串

截圖 2021-10-11 下午1.19.45

這時候他會自動幫你標示為SHA1,這樣就正確了

添加完成後就是如下畫面

這時候,點擊紅框部分下載json檔,下載好之後直接覆蓋進剛才的google-service.json檔案

截圖 2021-10-11 下午1.22.57

截圖 2021-10-11 下午1.35.33

給大家參考一下現在Json裡面的內容

google-services.json

{
  "project_info": {
    "project_number": "1082870549671",
    "project_id": "signinexample-a405e",
    "storage_bucket": "signinexample-a405e.appspot.com"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:1082870549671:android:9bb4c7493ecfe2a2bf5f82",
        "android_client_info": {
          "package_name": "com.noahliu.googlesigninexample",
          "certificate_hash": "1d0bdc9f793973d48078e93b69ef45ac8210fe2f"
        }
      },
      "oauth_client": [
        {
          "client_id": "1082870549671-hnq6kob2g02368r1vf1oal25hf0vpmu7.apps.googleusercontent.com",
          "client_type": 3
        }
      ],
      "api_key": [
        {
          "current_key": "AIzaSyD-I4xLyx2v6fHca-WioWrzYxfdYCPIY9E"
        }
      ],
      "services": {
        "appinvite_service": {
          "other_platform_oauth_client": [
            {
              "client_id": "1082870549671-hnq6kob2g02368r1vf1oal25hf0vpmu7.apps.googleusercontent.com",
              "client_type": 3
            }
          ]
        }
      }
    }
  ],
  "configuration_version": "1"
}

 

OK,寫到這裡大多數的操作都完成了

接下來就是進入到寫程式的階段囉 :D

 


 

3. 程式撰寫

 

兄弟姐妹們啊!!最困難的已經熬過去啦XD

接下來就是寫程式的部分

首先給你一下畫面

activity_main.xml

Screenshot_1633932536

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <com.google.android.gms.common.SignInButton
        android:id="@+id/button_SignIn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView_Result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="未登入"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_SignIn" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

然後程式

MainActivity.java

public class MainActivity extends AppCompatActivity {
    public static final String TAG = MainActivity.class.getSimpleName()+"My";

    private GoogleSignInClient mGoogleSignInClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("1082870549671-hnq6kob2g02368r1vf1oal25hf0vpmu7.apps.googleusercontent.com")
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        SignInButton btSighIn = findViewById(R.id.button_SignIn);
        btSighIn.setOnClickListener(v->{
            startActivityForResult(mGoogleSignInClient.getSignInIntent(),200);
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                String result = "登入成功\nEmail:"+account.getEmail()+"\nGoogle名稱:"
                        +account.getDisplayName();
                Log.d(TAG, "Token: "+account.getIdToken());
                TextView tvResult = findViewById(R.id.textView_Result);
                tvResult.setText(result);
            } catch (ApiException e) {
                Log.w(TAG, "Google sign in failed", e);
            }
        }
    }
}

 

基本上這些程式碼都是在Google官方都有提供的

甚至Google都還有寫範例XD

->點我

但是在59行這部分,他程式是有自動載入string檔案,不過不知為何我沒有QQ

所以在粉底白字那部分我是手動加入的

而來源就是這一串

截圖 2021-10-11 下午2.41.33

 

寫到這裡所有的設定都完成了,請試著執行看看吧!

 


 

老實說...這次的東西我最大的難題是標題不知道怎麼下XD

不知道為何,我發現好像寫這部分的文章好像很少,所以我就寫了~

而其實在實作的過程中也是一泊三折的,尤其是SHA-1的部分簡直差點令我抓狂(還好只抓狂一下下..)

好啦,那麼這篇文章就到這邊..

TK

arrow
arrow

    碼農日常 發表在 痞客邦 留言(14) 人氣()