如要讓使用者登入,請從瀏覽器的密碼管理工具擷取憑證,並使用這些憑證自動登入使用者。如果使用者有多個帳戶,可以透過帳戶選擇工具輕觸一下,選取所需帳戶。
自動登入
自動登入功能可在網站上的任何位置運作,不限於首頁,其他分葉頁面也適用。當使用者透過搜尋引擎連到網站上的不同網頁時,這項功能就非常實用。
如要啟用自動登入功能,請按照下列步驟操作:
- 取得憑證資訊。
- 驗證使用者。
- 更新 UI 或前往個人化頁面。
取得憑證資訊
如要取得憑證資訊,請叫用 navigator.credentials.get()。指定要要求的憑證類型,方法是提供 password 或 federated。
請一律使用 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() 傳回的 Promise 會解析為憑證物件或 null。如要判斷是 PasswordCredential 還是 FederatedCredential,只要查看物件的 .type 屬性即可,該屬性會是 password 或 federated。
如果 .type 為 federated,.provider 屬性會是代表識別資訊提供者的字串。
驗證使用者
取得憑證後,請根據憑證類型 (password 或 federated) 執行驗證流程:
}).then(c => {
if (c) {
switch (c.type) {
case 'password':
return sendRequest(c);
break;
case 'federated':
return gSignIn(c);
break;
}
} else {
return Promise.resolve();
}
當 Promise 解析時,請檢查是否已收到憑證物件。如果沒有,表示無法自動登入。 自動關閉自動登入程序。
更新 UI
如果驗證成功,請更新 UI 或將使用者轉送至個人化頁面:
}).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');
});
}
}
透過帳戶選擇工具登入
如果使用者需要調解或有多個帳戶,請使用帳戶選擇工具讓使用者登入,略過一般登入表單,例如:
透過帳戶選擇工具登入的步驟與自動登入相同,但需要額外呼叫顯示帳戶選擇工具,做為取得憑證資訊的一部分:
- 取得憑證資訊並顯示帳戶選擇工具。
- 驗證使用者。
- 更新 UI 或前往個人化頁面。
取得憑證資訊並顯示帳戶選擇工具
根據定義的使用者動作顯示帳戶選擇工具,例如使用者輕觸「登入」按鈕時。呼叫 navigator.credentials.get(),並新增 mediation: 'optional' 或 mediation: 'required',即可顯示帳戶選擇工具。
當 mediation 為 required 時,系統一律會向使用者顯示帳戶選擇工具,以便登入。這個選項可讓擁有多個帳戶的使用者輕鬆切換帳戶。如果 mediation 為 optional,系統會在 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 => {
使用者選取帳戶後,Promise 會以憑證解析。如果使用者取消帳戶選擇器,或沒有儲存的憑證,則 Promise 會解析為 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';
});
}
});
聯合登入
聯合登入功能可讓使用者輕觸一下就登入,不必記住網站的其他登入詳細資料。
如要實作聯合登入,請按照下列步驟操作:
- 使用第三方身分驗證使用者。
- 儲存身分資訊。
- 更新 UI 或前往個人化頁面 (與自動登入相同)。
使用第三方身分驗證使用者
使用者輕觸聯合登入按鈕時,請使用 FederatedCredential 執行特定識別資訊提供者驗證流程。
舉例來說,如果供應商是 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 Connect 或 OAuth 等標準通訊協定為基礎。如要瞭解如何使用聯合帳戶進行驗證,請參閱各聯合身分識別資訊提供者的說明文件。常見例子包括:
儲存身分資訊
驗證完成後,即可儲存身分資訊。您要儲存的資訊是識別資訊提供者的 id,以及代表識別資訊提供者的提供者字串 (name 和 iconURL 為選用)。如要進一步瞭解這項資訊,請參閱憑證管理規格。
如要儲存聯合帳戶詳細資料,請使用使用者的 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();
}
這樣一來,系統就不會自動登入,直到使用者下次啟用自動登入功能為止。 如要恢復自動登入,使用者可以從帳戶選擇工具中選擇要登入的帳戶,主動登入。之後,使用者會一律保持登入狀態,直到明確登出為止。