使用AWS Amplify中的Auth组件来设置Cognito TOTP(验证器),并通过使用Auth组件的步骤减少手动设置的代码行数。
以下是在React中使用AWS Amplify Auth组件设置Cognito TOTP时的示例代码:
npm install aws-amplify --save
import Amplify from 'aws-amplify';
Amplify.configure({ Auth: {
//指定AWS Cognito用户池的ID
userPoolId: 'YOUR_USER_POOL_ID',
//指定AWS Cognito用户池客户端ID
userPoolWebClientId: 'YOUR_USER_POOL_CLIENT_ID',
//配置MFA设置
mandatorySignIn: true,
authenticationFlowType: 'USER_PASSWORD_AUTH',
authenticatorComponents: ['MFA'],
//指定TOTP设置的短信和电子邮件模板
mfa: {
smsMessage: 'Your verification code is {####}',
emailSubject: 'Your verification code',
emailBody: 'Your verification code is {####}',
},
}, });
import { withAuthenticator, Authenticator } from 'aws-amplify-react';
class App extends Component {
render() {
return (
// Auth组件将显示TOTP设置的UI
export default withAuthenticator(App);
注意:withAuthenticator将渲染一个包含TOTP设置UI的登录表单。要同时显示TOTP设置和信息验证,需将authenticatorComponents值添加到Amplify配置中。
import { Auth } from 'aws-amplify';
// ...
//在Cognito中设置TOTP const setupTOTP = async () => { await Auth.verifyCurrentUserAttribute('email'); const { challengeName } = await Auth.setupTOTP(user); setMessage("Challenge sent to your email");
//手动请求用户输入TOTP验证代码 let auth_code = await Auth.confirmTOTP(user, challengeName, {inputFriendlyName: 'Authenticator number'});
//此处讲代码添加到Cognito中以启用TOTP await Auth.verifyTotpToken(auth_code);
//设置TOTP为有效 setMessage("Time-based One-time Password setup is