Search code examples
amazon-web-servicesaws-sdkamazon-cognitoaws-amplify

Adding multi factor authentication with AWS Amplify post signup?


If we have signed up a user via Google with AWS Cognito can we activate MFA later via the AWS Amplify API. If so what is the API Signature?

The general idea is to allow users to signin via a social provider at first, and if they are accessing areas / features of the platform that require MFA security, they can enable this by switching it on via their user profile.


Solution

  • This is from the Enabling TOTP section of the AWS Amplify API documentation

        import { Auth } from 'aws-amplify';
    
        // To setup TOTP, first you need to get a `authorization code` from Amazon Cognito
        // `user` is the current Authenticated user
        Auth.setupTOTP(user).then((code) => {
            // You can directly display the `code` to the user or convert it to a QR code to be scanned.
            // E.g., use following code sample to render a QR code with `qrcode.react` component:  
            //      import QRCode from 'qrcode.react';
            //      const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + code + "&issuer=" + issuer;
            //      <QRCode value={str}/>
        });
    
        // ...
    
        // Then you will have your TOTP account in your TOTP-generating app (like Google Authenticator)
        // Use the generated one-time password to verify the setup
        Auth.verifyTotpToken(user, challengeAnswer).then(() => {
    
            // don't forget to set TOTP as the preferred MFA method
            Auth.setPreferredMFA(user, 'TOTP');
            // ...
        }).catch( e => {
            // Token is not verified
        });