如需让用户登录,请从浏览器的密码管理器中检索凭据,并使用这些凭据自动让用户登录。对于拥有多个帐号的用户,您可以使用帐号选择器点按一下即可选择相应帐号。
自动登录
自动登录可发生在您网站上的任何位置;不仅是首页,还包括其他叶级页。当用户通过搜索引擎访问您网站上的各个网页时,这非常有用。
要启用自动登录,请执行以下操作:
- 获取凭据信息。
- 对用户进行身份验证。
- 更新界面或继续访问个性化页面。
获取凭据信息
如需获取凭据信息,请调用 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 解析后,请检查您是否收到了凭据对象。否则,将无法自动登录。 以静默方式关闭自动登录流程。
更新界面
如果身份验证成功,则更新界面或将用户转到个性化页面:
}).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');
});
}
}
通过账号选择器登录
如果用户需要使用中介或有多个帐号,请使用帐号选择器让用户登录,跳过普通的登录表单,例如:
通过帐号选择器登录的步骤与自动登录相同,只是在获取凭据信息的过程中还要调用并显示帐号选择器:
- 获取凭据信息,并显示帐号选择器。
- 对用户进行身份验证。
- 更新界面或继续访问个性化页面。
获取凭据信息并显示帐号选择器
在响应定义的用户操作(例如,当用户点按“登录”按钮时)时显示帐号选择器。调用 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';
});
}
});
联合登录
借助联合登录,用户只需点按一下即可登录,无需记住您网站的其他登录详细信息。
如需实现联合登录,请执行以下操作:
- 使用第三方身份对用户进行身份验证。
- 存储身份信息。
- 更新界面或继续访问个性化页面(与自动登录功能相同)。
使用第三方身份对用户进行身份验证
当用户点按联合登录按钮时,使用 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
是可选的)。如需详细了解此信息,请参阅凭据管理规范。
如需存储联合帐号详细信息,请使用用户的标识符和提供方的标识符实例化一个新的 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();
}
这样可以确保等到用户下次启用自动登录时,才会进行自动登录。 如需恢复自动登录,用户可从帐号选择器中选择想要用于登录的帐号,从而自行选择登录。这样一来,在他们明确退出之前,用户始终会重新登录。