透過 Apple 登入使用者

本文說明如何使用 Identity Platform,在網頁應用程式中加入「使用 Apple 登入」功能。

事前準備

  • 啟用 Identity Platform,並使用 HTML 和 JavaScript 編寫基本網頁應用程式。如要瞭解如何啟用 Identity Platform 及登入,請參閱快速入門

  • 加入 Apple 開發人員計畫

向 Apple 設定應用程式

在 Apple Developer 網站上:

  1. 按照「為網站設定『透過 Apple 登入』功能」中的步驟操作。 包括:

    1. 註冊回傳網址,格式如下:

      https://project-id.firebaseapp.com/__/auth/handler
      
    2. 在下列網址暫時代管檔案,以驗證網域:

      https://project-id.firebaseapp.com/.well-known/apple-developer-domain-association.txt
      

    此外,請記下「服務 ID」和「Apple 團隊 ID」,下一節會用到。

  2. 使用 Apple 私密金鑰建立登入功能。 下一節會用到金鑰 ID

  3. 如果您使用 Identity Platform 傳送電子郵件給使用者,請使用下列電子郵件透過 Apple 的私密電子郵件轉送服務設定專案

    noreply@project-id.firebaseapp.com
    

    如果應用程式有自訂電子郵件範本,也可以使用該範本。

遵守 Apple 的去識別化資料規定

Apple 讓使用者選擇匿名處理資料,包括電子郵件地址。選取這個選項後,Apple 會為使用者指派網域為 privaterelay.appleid.com 的模糊化電子郵件地址。

您的應用程式必須遵守 Apple 針對匿名 Apple ID 制定的所有適用開發人員政策或條款。包括在將任何個人識別資訊 (PII) 與匿名 Apple ID 建立關聯前,先徵求使用者同意。涉及 PII 的動作包括但不限於:

  • 將電子郵件地址連結至匿名 Apple ID,或反向操作。
  • 將電話號碼連結至匿名 Apple ID,或反向操作
  • 將非匿名社群憑證 (例如 Facebook 或 Google) 連結至匿名 Apple ID,反之亦然。

詳情請參閱 Apple 開發人員帳戶的《Apple 開發人員計畫授權協議》。

將 Apple 設為提供者

如要將 Apple 設定為識別資訊提供者,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「Identity Providers」(識別資訊提供者) 頁面。

    前往「Identity Providers」頁面

  2. 按一下「Add A Provider」

  3. 從清單中選取「Apple」

  4. 在「平台」下方,選取「網站」

  5. 輸入服務 IDApple 團隊 ID金鑰 ID私密金鑰

  6. 按一下「已授權網域」下方的「新增網域」,註冊應用程式的網域。為方便開發,localhost 預設為啟用狀態。

  7. 在「設定應用程式」下方,按一下「設定詳細資料」。將程式碼片段複製到應用程式的程式碼中,初始化 Identity Platform 用戶端 SDK。

  8. 按一下 [儲存]

透過用戶端 SDK 登入使用者

如何登入使用者:

  1. 使用 ID apple.com 建立 OAuthProvider 提供者物件的執行個體:

    網頁版 9

    import { OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('apple.com');

    網頁版 8

    var provider = new firebase.auth.OAuthProvider('apple.com');
  2. 選填:新增 OAuth 範圍。範圍會指定您向 Apple 要求的資料。如要存取更敏感的資料,可能需要特定範圍。根據預設,啟用「每個電子郵件地址只能建立一個帳戶」後,Identity Platform 會要求 emailname 範圍。

    網頁版 9

    provider.addScope('email');
    provider.addScope('name');

    網頁版 8

    provider.addScope('email');
    provider.addScope('name');
  3. 選用:將驗證流程在地化。你可以指定語言,或使用裝置的預設語言。如需支援的語言代碼,請參閱「使用 Apple 登入文件」。

    網頁版 9

    provider.setCustomParameters({
      // Localize the Apple authentication screen in French.
      locale: 'fr'
    });

    網頁版 8

    provider.setCustomParameters({
      // Localize the Apple authentication screen in French.
      locale: 'fr'
    });
  4. 使用提供者物件登入使用者。您可以開啟彈出式視窗,或重新導向目前的頁面。行動裝置使用者更容易重新導向。

    如要顯示彈出式視窗,請呼叫 signInWithPopup()

    網頁版 9

    import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .then((result) => {
        // The signed-in user info.
        const user = result.user;
    
        // Apple credential
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
    
        // 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 credential that was used.
        const credential = OAuthProvider.credentialFromError(error);
    
        // ...
      });

    網頁版 8

    firebase
      .auth()
      .signInWithPopup(provider)
      .then((result) => {
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // The signed-in user info.
        var user = result.user;
    
        // You can also get the Apple OAuth Access and ID Tokens.
        var accessToken = credential.accessToken;
        var idToken = credential.idToken;
    
        // IdP data available using getAdditionalUserInfo(result)
      // ...
      })
      .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;
    
        // ...
      });

    如要重新導向頁面,請先呼叫 signInWithRedirect()

    使用 signInWithRedirectlinkWithRedirectreauthenticateWithRedirect 時,請遵循最佳做法

    網頁版 9

    import { getAuth, signInWithRedirect } from "firebase/auth";
    
    const auth = getAuth();
    signInWithRedirect(auth, provider);

    網頁版 8

    firebase.auth().signInWithRedirect(provider);

    然後,在網頁載入時呼叫 getRedirectResult(),擷取 Apple 權杖:

    網頁版 9

    import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth";
    
    // Result from Redirect auth flow.
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        const credential = OAuthProvider.credentialFromResult(result);
        if (credential) {
          // You can also get the Apple OAuth Access and ID Tokens.
          const accessToken = credential.accessToken;
          const idToken = credential.idToken;
        }
        // The signed-in user info.
        const user = result.user;
      })
      .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 credential that was used.
        const credential = OAuthProvider.credentialFromError(error);
    
        // ...
      });

    網頁版 8

    // Result from Redirect auth flow.
    firebase
      .auth()
      .getRedirectResult()
      .then((result) => {
        if (result.credential) {
          /** @type {firebase.auth.OAuthCredential} */
          var credential = result.credential;
    
          // You can get the Apple OAuth Access and ID Tokens.
          var accessToken = credential.accessToken;
          var idToken = credential.idToken;
    
          // IdP data available in result.additionalUserInfo.profile.
          // ...
        }
        // The signed-in user info.
        var user = result.user;
      })
      .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;
    
        // ...
      });

    您也可以在這裡擷取及處理錯誤。如需錯誤代碼清單,請參閱 API 參考資料

與許多其他身分提供者不同,Apple 不會提供相片網址。

如果使用者選擇不與應用程式分享真實電子郵件地址,Apple 會提供專屬電子郵件地址供使用者分享。這封電子郵件的格式為 xyz@privaterelay.appleid.com。如果你設定了私人電子郵件轉送服務,Apple 會將寄至匿名地址的電子郵件轉寄至使用者的真實電子郵件地址。

Apple 只會在使用者首次登入時,與應用程式分享使用者資訊 (例如顯示名稱)。在大多數情況下,Identity Platform 會儲存這項資料,讓您在日後的工作階段中使用 firebase.auth().currentUser.displayName 擷取資料。不過,如果您在整合 Identity Platform 前,允許使用者透過 Apple 登入應用程式,系統就不會提供使用者資訊。

後續步驟