登入的使用者

米金凱爾尼
Meggin Kearney

如要登入使用者,請從瀏覽器的密碼管理工具擷取憑證,然後使用這些憑證自動登入使用者。擁有多個帳戶的使用者,可使用帳戶選擇工具,輕觸一下即可選取帳戶。

自動登入

網站在任何位置都能使用自動登入功能,除了首頁,也能進行其他分葉頁面。 如果使用者透過搜尋引擎前往您網站上的多個網頁,這項功能就非常實用。

如何啟用自動登入功能:

  1. 取得憑證資訊。
  2. 驗證使用者。
  3. 請更新使用者介面或繼續前往個人化頁面。

取得憑證資訊

瀏覽器支援

  • 51
  • 18
  • 60
  • 13

資料來源

如要取得憑證資訊,請叫用 navigator.credentials.get()。提供 passwordfederated,藉此指定要要求的憑證類型。

請一律使用 mediation: 'silent' 進行自動登入,這樣當使用者符合下列條件時,您就能輕鬆關閉程序:

  • 未儲存任何憑證。
  • 已儲存多個憑證。
  • 已登出。

取得憑證前,別忘了檢查使用者是否已登入:

if (window.PasswordCredential || window.FederatedCredential) {
  if (!user.isSignedIn()) {
    navigator.credentials.get({
      password: true,
      federated: {
        providers: ['https://accounts.google.com'],
      },
      mediation: 'silent',
    });
    // ...
  }
}

navigator.credentials.get() 傳回的承諾使用憑證物件或 null 解析。如要判斷這是 PasswordCredential 還是 FederatedCredential,只要查看物件的 .type 屬性即可,可能是 passwordfederated

如果 .typefederated.provider 屬性就是代表識別資訊提供者的字串。

驗證使用者

取得憑證後,根據憑證類型 (passwordfederated) 執行驗證流程:

    }).then(c => {
     if (c) {
       switch (c.type) {
         case 'password':
           return sendRequest(c);
           break;
         case 'federated':
           return gSignIn(c);
           break;
       }
     } else {
       return Promise.resolve();
     }

承諾解析完畢後,請檢查您是否收到憑證物件。否則無法自動登入。 關閉自動登入程序。

更新使用者介面

如果驗證成功,請更新使用者介面,或將使用者轉送至個人化頁面:

    }).then(profile => {
     if (profile) {
       updateUI(profile);
     }

別忘了顯示驗證錯誤訊息

為避免造成使用者混淆,使用者取得憑證物件時,應會看到顯示「登入」的藍色浮動式訊息:

顯示使用者正在登入的藍色浮動式訊息。

重要注意事項:如果您成功取得憑證物件,但並未驗證使用者,則應顯示錯誤訊息:

        }).catch(error => {
          showError('Sign-in Failed');
        });
      }
    }

完整程式碼範例

if (window.PasswordCredential || window.FederatedCredential) {
  if (!user.isSignedIn()) {
    navigator.credentials
      .get({
        password: true,
        federated: {
          providers: ['https://accounts.google.com'],
        },
        mediation: 'silent',
      })
      .then((c) => {
        if (c) {
          switch (c.type) {
            case 'password':
              return sendRequest(c);
              break;
            case 'federated':
              return gSignIn(c);
              break;
          }
        } else {
          return Promise.resolve();
        }
      })
      .then((profile) => {
        if (profile) {
          updateUI(profile);
        }
      })
      .catch((error) => {
        showError('Sign-in Failed');
      });
  }
}

透過帳戶選擇工具登入

如果使用者需要中介服務,或擁有多個帳戶,請使用帳戶選擇工具讓使用者登入,並略過一般的登入表單,例如:

Google 帳戶選擇工具顯示多個帳戶。

透過帳戶選擇工具登入的步驟與自動登入相同,但會額外呼叫要在取得憑證資訊時顯示帳戶選擇工具:

  1. 取得憑證資訊並顯示帳戶選擇工具。
  2. 驗證使用者
  3. 更新使用者介面或前往個人化頁面

取得憑證資訊並顯示帳戶選擇工具

顯示帳戶選擇工具以回應定義的使用者動作 (例如使用者輕觸「登入」按鈕時)。呼叫 navigator.credentials.get(),並新增 mediation: 'optional'mediation: 'required' 以顯示帳戶選擇工具。

如果 mediationrequired,使用者一律會看到可登入的帳戶選擇工具。這個選項可讓擁有多個帳戶的使用者輕鬆切換不同帳戶。 如果 mediationoptional,使用者會在 navigator.credentials.preventSilentAccess() 呼叫後明確顯示帳戶選擇工具,以便登入。這通常是確保使用者選擇登出或取消註冊後,系統不會自動登入。

顯示 mediation: 'optional' 的範例:

    var signin = document.querySelector('#signin');
    signin.addEventListener('click', e => {
     if (window.PasswordCredential || window.FederatedCredential) {
       navigator.credentials.get({
         password: true,
         federated: {
           providers: [
             'https://accounts.google.com'
           ]
         },
         mediation: 'optional'
       }).then(c => {

使用者選取帳戶後,承諾會以憑證解析。如果使用者取消帳戶選擇工具,或未儲存任何憑證,承諾項目就會使用 null 解析。 在這種情況下,請返回登入表單。

別忘了返回登入表單

應基於以下任一原因,改回使用登入表單:

  • 系統不會儲存任何憑證。
  • 使用者已關閉帳戶選擇工具,但未選取帳戶。
  • API 無法使用,
    }).then(profile => {
        if (profile) {
          updateUI(profile);
        } else {
          location.href = '/signin';
        }
    }).catch(error => {
        location.href = '/signin';
    });

完整程式碼範例

var signin = document.querySelector('#signin');
signin.addEventListener('click', (e) => {
  if (window.PasswordCredential || window.FederatedCredential) {
    navigator.credentials
      .get({
        password: true,
        federated: {
          providers: ['https://accounts.google.com'],
        },
        mediation: 'optional',
      })
      .then((c) => {
        if (c) {
          switch (c.type) {
            case 'password':
              return sendRequest(c);
              break;
            case 'federated':
              return gSignIn(c);
              break;
          }
        } else {
          return Promise.resolve();
        }
      })
      .then((profile) => {
        if (profile) {
          updateUI(profile);
        } else {
          location.href = '/signin';
        }
      })
      .catch((error) => {
        location.href = '/signin';
      });
  }
});

聯合登入

聯合登入可讓使用者只要輕觸一下即可登入,不必記住網站的其他登入詳細資料。

如何執行聯合登入:

  1. 使用第三方身分驗證使用者。
  2. 儲存身分資訊。
  3. 更新 UI 或前往個人化頁面 (與自動登入功能相同)。

透過第三方身分驗證使用者

當使用者輕觸聯合登入按鈕時,使用 FederatedCredential 執行特定的識別資訊提供者驗證流程。

瀏覽器支援

  • 51
  • 79
  • x
  • x

資料來源

舉例來說,如果供應商是 Google,請使用 Google 登入 JavaScript 程式庫

navigator.credentials
  .get({
    password: true,
    mediation: 'optional',
    federated: {
      providers: ['https://account.google.com'],
    },
  })
  .then(function (cred) {
    if (cred) {
      // Instantiate an auth object
      var auth2 = gapi.auth2.getAuthInstance();

      // Is this user already signed in?
      if (auth2.isSignedIn.get()) {
        var googleUser = auth2.currentUser.get();

        // Same user as in the credential object?
        if (googleUser.getBasicProfile().getEmail() === cred.id) {
          // Continue with the signed-in user.
          return Promise.resolve(googleUser);
        }
      }

      // Otherwise, run a new authentication flow.
      return auth2.signIn({
        login_hint: id || '',
      });
    }
  });

Google 登入會產生 ID 權杖,做為驗證證明。

一般來說,聯合登入是以 OpenID ConnectOAuth 等標準通訊協定為基礎。如要瞭解如何使用聯合帳戶進行驗證,請參閱個別的聯合識別資訊提供者說明文件。這類常見的例子包括:

儲存身分資訊

驗證完成後,您可以儲存身分資訊。您在這裡儲存的資訊是來自識別資訊提供者的 id,以及代表識別資訊提供者的提供者字串 (nameiconURL 為選用)。如要進一步瞭解這項資訊,請參閱 Credential Management 規格

如要儲存聯合帳戶的詳細資料,請使用使用者的 ID 和提供者 ID 將新的 FederatedCredential 物件例項化。然後叫用 navigator.credentials.store() 以儲存身分資訊。

成功聯盟後,以同步或非同步方式為 FederatedCredential 執行個體化:

同步方法範例:

// Create credential object synchronously.
var cred = new FederatedCredential({
  id: id, // id in IdP
  provider: 'https://account.google.com', // A string representing IdP
  name: name, // name in IdP
  iconURL: iconUrl, // Profile image url
});

非同步方法範例:

// Create credential object asynchronously.
var cred = await navigator.credentials.create({
  federated: {
    id: id,
    provider: 'https://accounts.google.com',
    name: name,
    iconURL: iconUrl,
  },
});

接著儲存憑證物件:

// Store it
navigator.credentials.store(cred).then(function () {
  // continuation
});

登出

在使用者輕觸登出按鈕後,將使用者登出。 請先終止工作階段,然後關閉日後造訪的自動登入功能。(終止會議的方式完全由您決定)。

關閉日後造訪時自動登入的功能

呼叫 navigator.credentials.preventSilentAccess()

signoutUser();
if (navigator.credentials && navigator.credentials.preventSilentAccess) {
  navigator.credentials.preventSilentAccess();
}

這樣會確保系統只有在使用者下次啟用自動登入功能時,才會執行自動登入。 如要繼續使用自動登入功能,使用者可以選擇透過帳戶選擇工具選擇要登入的帳戶,藉此主動登入。如此一來,除非使用者明確登出,否則使用者一律必須重新登入。

意見回饋: