您可以將 GitHub 驗證功能整合至應用程式,讓使用者透過 GitHub 帳戶驗證 Firebase。您可以使用 Firebase SDK 執行登入流程,或手動執行 GitHub OAuth 2.0 流程,然後將產生的存取權權杖傳遞至 Firebase,以整合 GitHub 驗證功能。
事前準備
- 將 Firebase 新增至 JavaScript 專案。
- 在 Firebase 控制台中,開啟「Auth」部分。
- 在「Sign in method」分頁中,啟用 GitHub 供應器。
- 將該供應商開發人員控制台的「用戶端 ID」和「用戶端密鑰」新增至供應商設定:
- 將應用程式註冊為 GitHub 上的開發人員應用程式,並取得應用程式的 OAuth 2.0 用戶端 ID 和 用戶端密碼。
- 請確認 Firebase OAuth 重新導向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
) 已設為 GitHub 應用程式設定中應用程式設定頁面的 授權回呼網址。
- 按一下 [儲存]。
使用 Firebase SDK 處理登入流程
如果您正在建構網路應用程式,透過 Firebase 驗證使用者 GitHub 帳戶最簡單的方法,就是使用 Firebase JavaScript SDK 處理登入流程。(如果您想在 Node.js 或其他非瀏覽器環境中驗證使用者,則必須手動處理登入流程)。
如要使用 Firebase JavaScript SDK 處理登入流程,請按照下列步驟操作:
- 建立 GitHub 提供者物件的例項:
import { GithubAuthProvider } from "firebase/auth"; const provider = new GithubAuthProvider();
var provider = new firebase.auth.GithubAuthProvider();
- 選用:指定您要向驗證提供者要求的其他 OAuth 2.0 範圍。如要新增範圍,請呼叫
addScope
。例如:provider.addScope('repo');
provider.addScope('repo');
- 選用:指定您要透過 OAuth 要求傳送的其他自訂 OAuth 供應器參數。如要新增自訂參數,請在已初始化的提供者上呼叫
setCustomParameters
,並使用物件提供 OAuth 提供者文件中指定的鍵和相應值。例如:provider.setCustomParameters({ 'allow_signup': 'false' });
provider.setCustomParameters({ 'allow_signup': 'false' });
- 使用 GitHub 供應器物件,透過 Firebase 進行驗證。您可以開啟彈出式視窗或重新導向至登入頁面,提示使用者使用 GitHub 帳戶登入。在行動裝置上,系統會優先採用重新導向方法。
- 如要透過彈出式視窗登入,請呼叫
signInWithPopup
:import { getAuth, signInWithPopup, GithubAuthProvider } from "firebase/auth"; const auth = getAuth(); signInWithPopup(auth, provider) .then((result) => { // This gives you a GitHub Access Token. You can use it to access the GitHub API. const credential = GithubAuthProvider.credentialFromResult(result); const token = credential.accessToken; // The signed-in user info. const user = result.user; // IdP data available using getAdditionalUserInfo(result) // ... }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = GithubAuthProvider.credentialFromError(error); // ... });
firebase .auth() .signInWithPopup(provider) .then((result) => { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a GitHub Access Token. You can use it to access the GitHub API. var token = credential.accessToken; // The signed-in user info. var user = result.user; // IdP data available in result.additionalUserInfo.profile. // ... }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
您也可以在這裡捕捉及處理錯誤。如需錯誤代碼清單,請參閱 Auth 參考文件。
- 如要透過重新導向登入頁面來登入,請呼叫
signInWithRedirect
: 使用 `signInWithRedirect` 時,請遵循最佳做法。import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
firebase.auth().signInWithRedirect(provider);
getRedirectResult
,藉此擷取 GitHub 供應器的 OAuth 權杖:import { getAuth, getRedirectResult, GithubAuthProvider } from "firebase/auth"; const auth = getAuth(); getRedirectResult(auth) .then((result) => { const credential = GithubAuthProvider.credentialFromResult(result); if (credential) { // This gives you a GitHub Access Token. You can use it to access the GitHub API. const token = credential.accessToken; // ... } // The signed-in user info. const user = result.user; // IdP data available using getAdditionalUserInfo(result) // ... }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = GithubAuthProvider.credentialFromError(error); // ... });
firebase.auth() .getRedirectResult() .then((result) => { if (result.credential) { /** @type {firebase.auth.OAuthCredential} */ var credential = result.credential; // This gives you a GitHub Access Token. You can use it to access the GitHub API. var token = credential.accessToken; // ... } // The signed-in user info. var user = result.user; // IdP data available in result.additionalUserInfo.profile. // ... }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... });
- 如要透過彈出式視窗登入,請呼叫
處理「account-exists-with-different-credential」錯誤
如果您在 Firebase 控制台中啟用「每個電子郵件地址一個帳戶」設定,當使用者嘗試使用另一個 Firebase 使用者供應商 (例如 Google) 的電子郵件地址登入供應商 (例如 GitHub) 時,系統會擲回錯誤 auth/account-exists-with-different-credential
和 AuthCredential
物件 (GitHub 存取權杖)。如要完成登入指定提供者的程序,使用者必須先登入現有提供者 (Google),然後連結至前述的 AuthCredential
(GitHub 存取權權杖)。
彈出式模式
如果您使用 signInWithPopup
,可以使用以下程式碼處理 auth/account-exists-with-different-credential
錯誤:
import { getAuth, linkWithCredential, signInWithPopup, GitHubAuthProvider, } from "firebase/auth"; try { // Step 1: User tries to sign in using GitHub. let result = await signInWithPopup(getAuth(), new GitHubAuthProvider()); } catch (error) { // Step 2: User's email already exists. if (error.code === "auth/account-exists-with-different-credential") { // The pending GitHub credential. let pendingCred = error.credential; // Step 3: Save the pending credential in temporary storage, // Step 4: Let the user know that they already have an account // but with a different provider, and let them choose another // sign-in method. } } // ... try { // Step 5: Sign the user in using their chosen method. let result = await signInWithPopup(getAuth(), userSelectedProvider); // Step 6: Link to the GitHub credential. // TODO: implement `retrievePendingCred` for your app. let pendingCred = retrievePendingCred(); if (pendingCred !== null) { // As you have access to the pending credential, you can directly call the // link method. let user = await linkWithCredential(result.user, pendingCred); } // Step 7: Continue to app. } catch (error) { // ... }
重新導向模式
在重新導向模式中,系統會以類似方式處理這項錯誤,但差別在於,系統必須在網頁重新導向期間快取待處理的憑證 (例如使用工作階段儲存空間)。
手動處理登入流程
您也可以透過呼叫 GitHub OAuth 2.0 端點,處理登入流程,進而使用 GitHub 帳戶透過 Firebase 進行驗證:
- 按照 開發人員文件中的說明,將 GitHub 驗證功能整合至應用程式。在 GitHub 登入流程結束時,您會收到 OAuth 2.0 存取權杖。
- 如果您需要在 Node.js 應用程式中登入,請將 OAuth 存取權憑證傳送至 Node.js 應用程式。
- 使用者成功登入 GitHub 後,請將 OAuth 2.0 存取權權杖換成 Firebase 憑證:
import { GithubAuthProvider } from "firebase/auth"; const credential = GithubAuthProvider.credential(token);
var credential = firebase.auth.GithubAuthProvider.credential(token);
- 使用 Firebase 憑證向 Firebase 進行驗證:
import { getAuth, signInWithCredential } from "firebase/auth"; // Sign in with the credential from the user. const auth = getAuth(); signInWithCredential(auth, credential) .then((result) => { // Signed in // ... }) .catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // ... });
// Sign in with the credential from the user. firebase.auth() .signInWithCredential(credential) .then((result) => { // Signed in // ... }) .catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.email; // ... });
在 Chrome 擴充功能中使用 Firebase 進行驗證
如果您要建構 Chrome 擴充功能應用程式,請參閱 離線文件指南。
自訂 GitHub 登入的重新導向網域
建立專案時,Firebase 會為專案提供專屬子網域:https://my-app-12345.firebaseapp.com
。
這也會用來做為 OAuth 登入的重新導向機制。您必須為所有支援的 OAuth 供應商允許該網域。不過,這也表示使用者在登入 GitHub 時,可能會看到以下網域,然後再重新導向至應用程式:Continue to: https://my-app-12345.firebaseapp.com。
如要避免顯示子網域,您可以使用 Firebase Hosting 設定自訂網域:
- 請按照「為 Hosting 設定網域」中的步驟 1 至 3 操作。驗證網域擁有權後,Hosting 會為自訂網域佈建 SSL 憑證。
- 將自訂網域新增至 Firebase 控制台的授權網域清單:
auth.custom.domain.com
。 - 在 GitHub 開發人員工作室或 OAuth 設定頁面中,將重新導向網頁的網址加入白名單,這樣您就能透過自訂網域存取該網頁:
https://auth.custom.domain.com/__/auth/handler
。 - 初始化 JavaScript 程式庫時,請使用
authDomain
欄位指定自訂網域:var config = { apiKey: '...', // Changed from '
PROJECT_ID .firebaseapp.com'. authDomain: 'auth.custom.domain.com', databaseURL: 'https://PROJECT_ID .firebaseio.com', projectId: 'PROJECT_ID ', storageBucket: ' ', messagingSenderId: 'PROJECT_ID .firebasestorage.appSENDER_ID ' }; firebase.initializeApp(config);
後續步驟
使用者首次登入後,系統會建立新使用者帳戶,並連結至使用者登入時所使用的憑證 (即使用者名稱和密碼、電話號碼或驗證服務提供者資訊)。這個新帳戶會儲存在 Firebase 專案中,無論使用者如何登入,都可以用於在專案中的每個應用程式中識別使用者。
-
在應用程式中,建議您在
Auth
物件上設定觀察器,以便瞭解使用者的驗證狀態。接著,您可以從User
物件取得使用者的基本個人資料資訊。請參閱「管理使用者」。 在 Firebase Realtime Database 和 Cloud Storage 安全性規則中,您可以從
auth
變數取得已登入使用者的專屬使用者 ID,並利用該 ID 控管使用者可存取的資料。
您可以將驗證服務供應商憑證連結至現有使用者帳戶,讓使用者透過多個驗證服務供應商登入應用程式。
如要將使用者登出,請呼叫
signOut
:
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });