From 86372fc62d00eaa9e00dab6363cfaf430e36dc89 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Mon, 11 Sep 2023 14:58:35 -0700 Subject: [PATCH 001/164] Update directory with new TOC wording --- src/directory/directory.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index fed0d273e7a..556465cb7f0 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -278,7 +278,7 @@ export const directory = { filters: ['js', 'react-native'] }, { - title: 'Multi-factor authentication', + title: 'Manage MFA settings', route: '/lib/auth/mfa', filters: ['js', 'react-native'] }, From 18db7bdd1fc1802c9976d005e243ab5da04eb369 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Mon, 11 Sep 2023 17:11:05 -0700 Subject: [PATCH 002/164] Updated MFA guide for JS --- .../lib/auth/mfa/q/platform/[platform].mdx | 720 +++++++++++++++++- 1 file changed, 717 insertions(+), 3 deletions(-) diff --git a/src/pages/lib/auth/mfa/q/platform/[platform].mdx b/src/pages/lib/auth/mfa/q/platform/[platform].mdx index c65900319cb..78f6a20a43f 100644 --- a/src/pages/lib/auth/mfa/q/platform/[platform].mdx +++ b/src/pages/lib/auth/mfa/q/platform/[platform].mdx @@ -1,11 +1,725 @@ export const meta = { - title: `Multi-factor authentication`, + title: `Manage MFA settings`, description: `Learn how to enable multi-factor authentication with Amplify.`, }; -import js0 from "/src/fragments/lib/auth/js/mfa.mdx"; +[comment]: # (source content from /src/fragments/lib/auth/js/mfa.mdx ; /src/fragments/lib/auth/js/emailpassword.mdx ; /src/fragments/lib/auth/common/device_features/common.mdx ; /src/fragments/lib/auth/js/device_features/10_rememberDevice.mdx ; /src/fragments/lib/auth/js/device_features/20_forgetDevice.mdx ; /src/fragments/lib/auth/js/device_features/30_fetchDevice.mdx) - + + +MFA (Multi-factor authentication) increases security for your app by adding an authentication method and not relying solely on the username (or alias) and password. In this guide we will review how you can set up MFA using Time-based-One-Time Passwords (TOTP) and Short Message Service (SMS). This includes understanding when to use TOTP or SMS as a second layer with your MFA and the tradeoffs between these models to help you choose the right model for your application. We’ll also review how to set up MFA to forget devices and additional advanced use cases. + +Before you begin you will need: +- An Amplify project with the Auth category configured +- The Amplify libraries installed and configured +- Access to your AWS account phone number if using SMS (for testing) + +## Enable and Disable MFA + +AWS Amplify uses Amazon Cognito to provide MFA. You will first enable MFA for your Cognito User Pool and then set up MFA for your app. Please see the [*Amazon Cognito Developer Guide*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html) for more information to set up MFA in Amazon Cognito. You use the same Cognito console to enable or disable MFA. + +When enabling MFA you will have two key decisions to make: +- **MFA enforcement:** As part of this setup you will determine how MFA is enforced. If you "Require MFA", all your users will need to complete MFA to sign in. If you you choose "Optional MFA", your users will have the choice on if they use MFA or not. +- **MFA methods:** You will also specify which MFA method you are using - TOTP (Time-based One-time Password) or SMS (Short Message Service). We recommend that you use TOTP-based MFA as it is more secure and you can reserve SMS for account recovery. + + + +| | Time-based One-time Password (TOTP) | Short Message Service (SMS) | +|:--|:--|:--| +| **Description** | Generates a short-lived numeric code for user authentication that includes a shared secret key and current time using an authenticator app. | Generates a one-time code shared via text message that is entered with other credentials for user authentication. | +| **Benefits** | More secure than SMS since the code is generated locally and not transmitted over a network. TOTP also works without cell service as long as the TOTP app is installed. | Easy to set up with a user-provided phone number and is familiar to users as a common authentication method. | +| **Constraints** | Requires an app to generate codes and adds to the initial setup of an account. Codes also expire quickly and must be used promptly after it is generated. | SMS requires cell service and can include an additional cost for the user. Although rare, SMS messages can also be intercepted. | + + + +
+ +After you enable MFA you will also need to include MFA setup when users sign up. This will change depending on if you choose TOTP, SMS, or both. + +### Set up TOTP + +You can add Time-based One-time Password (TOTP) to your app which will ask users to complete authentication using a time-based one-time password (TOTP) after their username and password are verified. These TOTPs are generated using software token authentication apps like "Google Authenticator". When TOTP MFA is set up your user will be presented with a private key or QR code that they must enter into the TOTP-generating app. This app will then begin generating codes for the user to use for subsequent sign-in sessions. + +You can set up TOTP for a user in your app with the `setupTOTPAuth` method. As part of this workflow you can also specify how users see the code retrieved from the authenticator app (e.g. numeric code or QR code), confirm the initial setup with the authenticator app, set TOTP as the preferred MFA method, and pass the TOTP code with the MFA type using the `confirmSignIn` method: + + + + +```ts +import { CognitoUserSession } from 'amazon-cognito-identity-js'; +import { Auth } from 'aws-amplify'; + +type SetupTOTPAuthParameters = { + user: string; + challengeAnswer: string; + mfaType?: 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; +}; + +export async function setupTOTPAuth({ user, challengeAnswer, mfaType }: SetupTOTPAuthParameters) { + // To set up TOTP, first you need to get a `authorization code` from Amazon Cognito. + // `user` is the current Authenticated user: + const secretCode = await Auth.setupTOTP(user); + + // You can directly display the `code` to the user or convert it to a QR code to be scanned. + // For example, use following code sample to render a QR code with `qrcode.react` component: + // import QRCodeCanvas from 'qrcode.react'; + // const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + secretCode + "&issuer=" + issuer; + // + + // ... + + // 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. + try { + const cognitoUserSession: CognitoUserSession = await Auth.verifyTotpToken( + user, + challengeAnswer + ); + // Don't forget to set TOTP as the preferred MFA method. + await Auth.setPreferredMFA(user, 'TOTP'); + } catch (error) { + // Token is not verified + } + + // ... + + // Finally, when sign-in with MFA is enabled, use the `confirmSignIn` method + // to pass the TOTP code and MFA type. + const OTPCode = '123456'; // Code retrieved from authenticator app. + await Auth.confirmSignIn(user, OTPCode, mfaType); // Optional, MFA Type e.g. SMS_MFA || SOFTWARE_TOKEN_MFA +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function setupTOTPAuth(user, challengeAnswer, mfaType) { + // To set up TOTP, first you need to get a `authorization code` from Amazon Cognito. + // `user` is the current Authenticated user: + const OTPCode = '123456'; // Code retrieved from authenticator app. + + // You can directly display the `code` to the user or convert it to a QR code to be scanned. + // For example, use following code sample to render a QR code with `qrcode.react` component: + // import QRCodeCanvas from 'qrcode.react'; + // const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + code + "&issuer=" + issuer; + // + + // ... + + // 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. + try { + const cognitoUserSession = await Auth.verifyTotpToken(user, challengeAnswer); + // Don't forget to set TOTP as the preferred MFA method. + await Auth.setPreferredMFA(user, 'TOTP'); + } catch (error) { + // Token is not verified + } + + // ... + + // Finally, when sign-in with MFA is enabled, use the `confirmSignIn` method + // to pass the TOTP code and MFA type. + await Auth.confirmSignIn(user, code, mfaType); // Optional, MFA Type e.g. SMS_MFA || SOFTWARE_TOKEN_MFA +} +``` + + + + + +There are few limitations for TOTP MFA to keep in mind: +1. Amazon Cognito does not support hardware-based MFA. Use a software token MFA through an authenticator app that generates TOTP codes. +2. When TOTP is required your user must register with an authenticator app or subsequent sign-in attempts will fail. +3. Your users can use TOTP for MFA even if you disable TOTP for the user pool later. + +To learn more details review the [*Amazon Cognito TOTP software token MFA*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-totp.html) documentation. + + + +### Set up SMS + +You can also use Short Message Service (SMS) as a second layer of authentication with MFA. When SMS is enabled, your users will get an authentication code via a text message to complete sign-in after they sign in with their username and password. + +After you enable MFA with Amazon Cognito, you will also need to configure an IAM role to use with Amazon Simple Notification Service (Amazon SNS) to manage SMS messages. You will then add this role under the "Messaging" tab for your user pool in the Amazon Cognito console. For additional information see the [*Amazon Cognito SMS text message MFA*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-sms-text-message.html) documentation. + + + +**Note:** If you create or update an SMS MFA configuration for your Cognito user pool, the Cognito service will send a test SMS message to an internal number in order to verify your configuration. You will be charged for these test messages by Amazon SNS. + +For information about Amazon SNS pricing, see [Worldwide SMS Pricing](https://aws.amazon.com/sns/sms-pricing/). + + + +You will then want to update your app UI to prompt your users to enter their phone number to receive SMS codes. Then, when a user signs in, Amazon Cognito responds with a challenge that requires the user to provide an SMS verification code. This is where you can trigger `Auth.confirmSignIn()` and pass in the code provided by the user. Amplify will then verify with Cognito that the SMS code is valid and complete the sign-in process by returning access, ID, and refresh tokens that are all handled by Amplify internally. Once the user completes the SMS text message flow their phone number is marked as verified in your user pool. + + + + +```ts +import { Auth } from 'aws-amplify'; + +type ConfirmSignInWithMFAParameters = { + username: string; + password: string; +}; + +type MFAType = 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; + +export async function signInWithMFA({ username, password }: ConfirmSignInWithMFAParameters) { + try { + const user = await Auth.signIn(username, password); + if (user.challengeName === 'SMS_MFA' || user.challengeName === 'SOFTWARE_TOKEN_MFA') { + // You need to get the code from the UI inputs + // and then trigger the following function with a button click. + const code: string = await getCodeFromUserInput(); + const mfaType: MFAType = await getMFATypeFromUserInput(); + // If MFA is enabled, sign-in should be confirmed with the confirmation code: + const loggedUser = await Auth.confirmSignIn( + user, // Return object from Auth.signIn() + code, // Confirmation code + mfaType // MFA Type e.g. SMS_MFA, SOFTWARE_TOKEN_MFA + ); + console.log(loggedUser); + } else { + // The user directly signs in: + console.log(user); + } + } catch (error) { + console.log(`error signing in`, error); + } +} + +async function getCodeFromUserInput(): Promise { + // fetch code using a user form input +} +async function getMFATypeFromUserInput(): Promise { + // fetch MFA type from user form input +} +``` + + + +```javascript +import { Auth } from 'aws-amplify'; + +async function signInWithMFA() { + try { + const user = await Auth.signIn(username, password); + if ( + user.challengeName === 'SMS_MFA' || + user.challengeName === 'SOFTWARE_TOKEN_MFA' + ) { + // You need to get the code from the UI inputs + // and then trigger the following function with a button click. + const code = getCodeFromUserInput(); + const mfaType = getMFATypeFromUserInput(); + // If MFA is enabled, sign-in should be confirmed with the confirmation code + const loggedUser = await Auth.confirmSignIn( + user, // Return object from Auth.signIn() + code, // Confirmation code + mfaType // MFA Type e.g. SMS_MFA, SOFTWARE_TOKEN_MFA + ); + console.log(loggedUser) + } else { + // The user directly signs in + console.log(user) + } + } catch (error) { + console.log(`error signing in`, error); + } +}; +``` + + + +### Set up MFA preferred type + +Both TOTP MFA and SMS MFA methods are supported by Amazon Cognito. If you provide the option for your users to choose their second authentication factor or opt out, then you will want to also save that preference for future sessions with the `setupMFAType` method: + + + + +```ts +import { Auth } from 'aws-amplify'; + + +export async function setupMFAType() { + // You can select preferred mfa type, for example: + // Select TOTP as preferred. + try { + const user = await Auth.currentAuthenticatedUser(); + const data = await Auth.setPreferredMFA(user, 'TOTP'); + console.log(data); + } catch (error) { + console.log('error setting up MFA type', error); + } + + // Select SMS as preferred. + await Auth.setPreferredMFA(user, 'SMS'); + + // Select no-mfa. + await Auth.setPreferredMFA(user, 'NOMFA'); +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +const user = await Auth.currentAuthenticatedUser(); +async function setupMFAType(user) { + // You can select preferred mfa type, for example: + // Select TOTP as preferred. + try { + const data = await Auth.setPreferredMFA(user, 'TOTP'); + console.log(data); + } catch (error) { + console.log('error setting up MFA type', error); + } + +// Select SMS as preferred. + await Auth.setPreferredMFA(user, 'SMS'); + + // Select no-mfa. + await Auth.setPreferredMFA(user, 'NOMFA'); +} +``` + + + +#### Retrieve current preferred MFA method + +Once the preferred MFA method is set for your user you will then want to use the `getPreferredMFAType` method to call this preference for future sign-in confirmations: + + + + +```ts +import { Auth } from 'aws-amplify'; + + +export async function getPreferredMFAType() { + try { + // Will retrieve the current mfa type from cache + // `bypassCache` is optional, by default is false. + // If set to true, it will get the MFA type from server + // side instead of from local cache. + const user = await Auth.currentAuthenticatedUser(); + const data = await Auth.getPreferredMFA(user, { bypassCache: false }); + console.log('Current preferred MFA type is: ' + data); + } catch (err) { + console.log(err) + } +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function getPreferredMFAType() { +try { + // Will retrieve the current mfa type from cache + // bypassCache is optional, by default is false. + // If set to true, it will get the MFA type from server + // side instead of from local cache. + const user = await Auth.currentAuthenticatedUser(); + const data = await Auth.getPreferredMFA(user, { bypassCache: false }); + console.log('Current preferred MFA type is: ' + data); + } catch (err) { + console.log(err) + } +} + +``` + + + + + +To avoid unexpected responses from Cognito, it is recommended to call `Auth.setPreferredMFA()` to ensure a user has set their MFA method *before* retrieving MFA settings with `Auth.getPreferredMFA()`. + + + + + +When signing in with user name and password, your user will either sign in directly or be asked to pass challenges to be authenticated. The `user` object returned from `Auth.signIn` will contain `challengeName` and `challengeParam` if the user needs to pass those challenges. You can call corresponding functions based on these two parameters. + +Challenge Name: + +- `SMS_MFA`: The user needs to input the code received from SMS message. You can submit the code by `Auth.confirmSignIn`. +- `SOFTWARE_TOKEN_MFA`: The user needs to input the OTP(one time password). You can submit the code by `Auth.confirmSignIn`. +- `NEW_PASSWORD_REQUIRED`: This happens when the user account is created through the Cognito console. The user needs to input the new password and required attributes. You can submit those data by `Auth.completeNewPassword`. +- `MFA_SETUP`: This happens when the MFA method is TOTP (time-based one time password) which requires the user to go through additional steps to generate passwords with an Authenticator app. You can start the setup process using `setupTOTPAuth`. +- `SELECT_MFA_TYPE`: This happens when both SMS and TOTP methods are enabled but neither is set as preferred. You can set up your frontend application to let users choose what type they want to use in the current session and set it using the `user.sendMFASelectionAnswer` function. + +The following code is only to demonstrate these options: + + + + +```ts +import { Auth } from 'aws-amplify'; + +type SignInParameters = { + username: string; + password: string; + mfaType?: 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; +}; + +type UserInput = { + username: string; + email: string; + phone_number: string; +}; + +export async function signIn({ username, password, mfaType }: SignInParameters) { + try { + const user = await Auth.signIn(username, password); + if (user?.challengeName === 'SMS_MFA' || user?.challengeName === 'SOFTWARE_TOKEN_MFA') { + // You need to get the code from the UI inputs + // and then trigger the following function with a button click + const code: string = await getCodeFromUserInput(); + // If MFA is enabled, sign-in should be confirmed with the confirmation code + const loggedUser = await Auth.confirmSignIn( + user, // Return object from Auth.signIn() + code, // Confirmation code + mfaType // MFA Type e.g. SMS_MFA, SOFTWARE_TOKEN_MFA + ); + } else if (user?.challengeName === 'NEW_PASSWORD_REQUIRED') { + const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number'] + // You need to get the new password and required attributes from the UI inputs + // and then trigger the following function with a button click + // For example, the email and phone_number are required attributes + const { username, email, phone_number }: UserInput = + await getInfoFromUserInput(); + const loggedUser = await Auth.completeNewPassword( + user, // the Cognito User Object + newPassword, // the new password + // OPTIONAL, the required attributes + { + email, + phone_number, + } + ); + } else if (user?.challengeName === 'MFA_SETUP') { + // This happens when the MFA method is TOTP + // The user needs to setup the TOTP before using it + // More info please check the Enabling MFA part + await Auth.setupTOTP(user); + } else if (user?.challengeName === 'SELECT_MFA_TYPE') { + // You need to get the MFA method (SMS or TOTP) from user + // and trigger the following function + // user object needs to be CognitoUser type + user.sendMFASelectionAnswer(mfaType, { + onFailure: (err: Error) => { + console.error(err); + }, + mfaRequired: (challengeName, parameters) => { + // Auth.confirmSignIn with SMS code + }, + totpRequired: (challengeName, parameters) => { + // Auth.confirmSignIn with TOTP code + }, + }); + } else { + // The user directly signs in + console.log(user); + } + } catch (err) { + if (err?.code === 'UserNotConfirmedException') { + // The error happens if the user didn't finish the confirmation step when signing up + // In this case you need to resend the code and confirm the user + // About how to resend the code and confirm the user, please check the signUp part + } else if (err?.code === 'PasswordResetRequiredException') { + // The error happens when the password is reset in the Cognito console + // In this case you need to call forgotPassword to reset the password + // Please check the Forgot Password part. + } else if (err?.code === 'NotAuthorizedException') { + // The error happens when the incorrect password is provided + } else if (err?.code === 'UserNotFoundException') { + // The error happens when the supplied username/email does not exist in the Cognito user pool + } else { + console.log(err); + } + } +} + +async function getCodeFromUserInput(): Promise { + // fetch code using a user form input +} +async function getInfoFromUserInput(): Promise { + // fetch user inputs like username, email and phoneNumber +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function signIn() { + try { + const user = await Auth.signIn(username, password); + if (user?.challengeName === 'SMS_MFA' || user?.challengeName === 'SOFTWARE_TOKEN_MFA') { + // You need to get the code from the UI inputs + // and then trigger the following function with a button click + const code = await getCodeFromUserInput(); + // If MFA is enabled, sign-in should be confirmed with the confirmation code + const loggedUser = await Auth.confirmSignIn( + user, // Return object from Auth.signIn() + code, // Confirmation code + mfaType // MFA Type e.g. SMS_MFA, SOFTWARE_TOKEN_MFA + ); + } else if (user?.challengeName === 'NEW_PASSWORD_REQUIRED') { + const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number'] + // You need to get the new password and required attributes from the UI inputs + // and then trigger the following function with a button click + // For example, the email and phone_number are required attributes + const { username, email, phone_number } = await getInfoFromUserInput(); + const loggedUser = await Auth.completeNewPassword( + user, // the Cognito User Object + newPassword, // the new password + // OPTIONAL, the required attributes + { + email, // from user input + phone_number, // from user input + } + ); + } else if (user?.challengeName === 'MFA_SETUP') { + // This happens when the MFA method is TOTP + // The user needs to setup the TOTP before using it + // More info please check the Enabling MFA part + await Auth.setupTOTP(user); + } else if (user?.challengeName === 'SELECT_MFA_TYPE') { + // You need to get the MFA method (SMS or TOTP) from user + // and trigger the following function + // user object needs to be CognitoUser type + user.sendMFASelectionAnswer(mfaType, { + onFailure: (err) => { + console.error(err); + }, + mfaRequired: (challengeName, parameters) => { + // Auth.confirmSignIn with SMS code + }, + totpRequired: (challengeName, parameters) => { + // Auth.confirmSignIn with TOTP code + }, + }); + } else { + // The user directly signs in + console.log(user); + } + } catch (err) { + if (err?.code === 'UserNotConfirmedException') { + // The error happens if the user didn't finish the confirmation step when signing up + // In this case you need to resend the code and confirm the user + // About how to resend the code and confirm the user, please check the signUp part + } else if (err?.code === 'PasswordResetRequiredException') { + // The error happens when the password is reset in the Cognito console + // In this case you need to call forgotPassword to reset the password + // Please check the Forgot Password part. + } else if (err?.code === 'NotAuthorizedException') { + // The error happens when the incorrect password is provided + } else if (err?.code === 'UserNotFoundException') { + // The error happens when the supplied username/email does not exist in the Cognito user pool + } else { + console.log(err); + } + } +} + +async function getCodeFromUserInput() { + // fetch code using a user form input +} +async function getInfoFromUserInput() { + // fetch user inputs like username, email and phoneNumber +} +``` + + + + + +
+ +You can now enable multi-factor authentication and specify your second authentication method with TOTP or SMS. Your users can set their preferred method and you can retrieve this for them when they sign in. You can now look to add features like remembering a device to reduce friction in the sign-in workflow. + +## Remember a device + +Remembering a device is useful in conjunction with MFA because it allows the second factor requirement to be automatically met when your user signs in on that device, thereby reducing friction in their sign-in experience. + + + +**Note:** The [device tracking and remembering](https://aws.amazon.com/blogs/mobile/tracking-and-remembering-devices-using-amazon-cognito-your-user-pools/) features are currently not available within the library when using the federated OAuth flow with Cognito User Pools or Hosted UI. + + + +### Configure the Amplify Auth Category + +You can enable the remembered device functionality in the Cognito User Pool console. To begin, go to your project directory and issue the command: + +```bash +amplify auth console +``` + +Select the following option to open the Cognito User Pool console: + +```bash +? Which Console + User Pool +``` + +When the console opens, scroll down to the "Device Tracking" section and select the "Edit" button. This will render the following page allowing you to configure your preference for remembering a user's device. + +![Edit device tracking options list is shown, with the don't remember highlighted.](/images/auth/webconsole_remember1.png) + +Choose either "Always remember" to remember a user's device by default or "User Opt-in" to give the user the ability to choose. + +When MFA is enabled you will have the option to suppress the second factor during multi-factor authentication. Choose "Yes" if you want a remembered device to be used as a second factor mechanism. + +![Options for allow users to bypass MFA for trusted devices.](/images/auth/webconsole_remember2.png) + +When you have made your selection(s), click "Save changes". You are now ready to start updating your code to manage remembered devices. + + + +There are differences to keep in mind when working with remembered, forgotten, and tracked devices. + +* **Tracked:** Every time the user signs in with a new device, the client is given the device key at the end of a successful authentication event. We use this device key to generate a salt and password verifier which is used to call the `ConfirmDevice` API. At this point, the device is considered to be "tracked". Once the device is in a tracked state, you can use the Amazon Cognito console to see the time it started to be tracked, last authentication time, and other information about that device. +* **Remembered:** Remembered devices are also tracked. During user authentication, the device key and secret pair assigned to a remembered device is used to authenticate the device to verify that it is the same device that the user previously used to sign in. +* **Not Remembered:** A not-remembered device is a tracked device where Cognito has been configured to require users to "Opt-in" to remember a device but the user has chosen not to remember the device. This use case is for users signing into their application from a device that they don't own. +* **Forgotten:** In the event that you no longer want to remember or track devices, you can use the `Auth.forgetDevice()` API to remove devices from being both remembered and tracked. + + + +### Remember devices + +You can remember devices using the following: + + + + +```ts +import { Auth } from 'aws-amplify'; + +export async function rememberDevice() { + try { + const result = await Auth.rememberDevice(); + console.log(result); + } catch (error) { + console.log('Error remembering device', error); + } +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function rememberDevice() { + try { + const result = await Auth.rememberDevice(); + console.log(result); + } catch (error) { + console.log('Error remembering device', error); + } +} +``` + + + +### Forget devices + +You can also forget devices but note that forgotten devices are still tracked. + + + + +```ts +import { Auth } from 'aws-amplify'; + +export async function forgetDevice() { + try { + await Auth.forgetDevice(); + } catch (error) { + console.log('Error forgetting device', error); + } +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function forgetDevice() { + try { + await Auth.forgetDevice(); + } catch (error) { + console.log('Error forgetting device', error); + } +} +``` + + + +### Fetch devices + +You can fetch a list of remembered devices by using the following: + + + + +```ts +import { Auth } from 'aws-amplify'; + +export async function fetchDevices() { + try { + const result = await Auth.fetchDevices(); + console.log(result); + } catch (err) { + console.log('Error fetching devices', err); + } +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function fetchDevices() { + try { + const result = await Auth.fetchDevices(); + console.log(result); + } catch (err) { + console.log('Error fetching devices', err); + } +} +``` + + + +You can now set up devices to be remembered, forgotten, and fetched. + +## Conclusion + +Congratulations! You finished the **Manage MFA settings** guide. In this guide, you set up and configured MFA for your users and provided them options on remembering their MFA preferences and devices. + +## Next steps + +Now that you completed setting up multi-factor authentication you may also want to add additional customization. We recommend you learn more about: +* [Switching authentication flows](/lib/auth/switch-auth/q/platform/js/) +* [Advanced workflows](/lib/auth/advanced/q/platform/js/) + +
import reactnative0 from "/src/fragments/lib/auth/js/mfa.mdx"; From 3e2ed50f85eabf2982822ea27098b24bec1ea5f4 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Mon, 11 Sep 2023 17:20:15 -0700 Subject: [PATCH 003/164] Updating directory to align with other platforms --- src/directory/directory.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index 556465cb7f0..9d332560a71 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -278,7 +278,7 @@ export const directory = { filters: ['js', 'react-native'] }, { - title: 'Manage MFA settings', + title: 'Manage Multi-factor authentication settings', route: '/lib/auth/mfa', filters: ['js', 'react-native'] }, From 2c772394e8ef10ac151195306c24e873eb3c982a Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Tue, 12 Sep 2023 13:35:43 -0700 Subject: [PATCH 004/164] Update common content from Flutter revisions --- .../lib/auth/mfa/q/platform/[platform].mdx | 581 +++++++++--------- 1 file changed, 280 insertions(+), 301 deletions(-) diff --git a/src/pages/lib/auth/mfa/q/platform/[platform].mdx b/src/pages/lib/auth/mfa/q/platform/[platform].mdx index 78f6a20a43f..4381972d141 100644 --- a/src/pages/lib/auth/mfa/q/platform/[platform].mdx +++ b/src/pages/lib/auth/mfa/q/platform/[platform].mdx @@ -1,25 +1,30 @@ export const meta = { - title: `Manage MFA settings`, + title: `Manage Multi-factor authentication settings`, description: `Learn how to enable multi-factor authentication with Amplify.`, }; -[comment]: # (source content from /src/fragments/lib/auth/js/mfa.mdx ; /src/fragments/lib/auth/js/emailpassword.mdx ; /src/fragments/lib/auth/common/device_features/common.mdx ; /src/fragments/lib/auth/js/device_features/10_rememberDevice.mdx ; /src/fragments/lib/auth/js/device_features/20_forgetDevice.mdx ; /src/fragments/lib/auth/js/device_features/30_fetchDevice.mdx) +[comment]: # (source content from /src/fragments/lib/auth/js/mfa.mdx ; /src/fragments/lib/auth/js/emailpassword.mdx ; /src/fragments/lib/auth/common/device_features/common.mdx ; /src/fragments/lib/auth/js/device_features/10_rememberDevice.mdx ; /src/fragments/lib/auth/js/device_features/20_forgetDevice.mdx ; /src/fragments/lib/auth/js/device_features/30_fetchDevice.mdx ; /lib/auth/mfa/q/platform/flutter/) -MFA (Multi-factor authentication) increases security for your app by adding an authentication method and not relying solely on the username (or alias) and password. In this guide we will review how you can set up MFA using Time-based-One-Time Passwords (TOTP) and Short Message Service (SMS). This includes understanding when to use TOTP or SMS as a second layer with your MFA and the tradeoffs between these models to help you choose the right model for your application. We’ll also review how to set up MFA to forget devices and additional advanced use cases. +The Auth category supports Multi-factor Authentication (MFA) for user sign-in flows. MFA is an extra layer of security used to make sure that users trying to gain access to an account are who they say they are. It requires users to provide additional information to verify their identity. The category supports the MFA methods with Time-based-One-Time Passwords (TOTP) and Short Message Service (SMS). In this guide we will review how you can set up MFA using TOTP and SMS and the tradeoffs between these methods to help you choose the right set up for your application. We’ll also review how to set up MFA to forget devices and additional advanced use cases. Before you begin you will need: -- An Amplify project with the Auth category configured - The Amplify libraries installed and configured - Access to your AWS account phone number if using SMS (for testing) -## Enable and Disable MFA +## Enable Multi-factor authentication with the Amplify CLI -AWS Amplify uses Amazon Cognito to provide MFA. You will first enable MFA for your Cognito User Pool and then set up MFA for your app. Please see the [*Amazon Cognito Developer Guide*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html) for more information to set up MFA in Amazon Cognito. You use the same Cognito console to enable or disable MFA. +Below are the steps you can use to set up MFA using SMS or TOTP with the Amplify CLI. The Amplify libraries are designed to work with MFA even if you have set up your Amazon Cognito resources separately. + + + +You can also use the Amazon Cognito console to enable MFA. You will first enable MFA for your Cognito User Pool and then set up MFA for your app. Please see the [*Amazon Cognito Developer Guide*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html) for more information to set up MFA in Amazon Cognito. You can use the same Cognito console to enable or disable MFA. + + When enabling MFA you will have two key decisions to make: -- **MFA enforcement:** As part of this setup you will determine how MFA is enforced. If you "Require MFA", all your users will need to complete MFA to sign in. If you you choose "Optional MFA", your users will have the choice on if they use MFA or not. +- **MFA enforcement:** As part of this setup you will determine how MFA is enforced. If you require MFA by setting to "ON", all your users will need to complete MFA to sign in. If you keep it "Optional", your users will have the choice on if they use MFA or not. - **MFA methods:** You will also specify which MFA method you are using - TOTP (Time-based One-time Password) or SMS (Short Message Service). We recommend that you use TOTP-based MFA as it is more secure and you can reserve SMS for account recovery. @@ -34,126 +39,179 @@ When enabling MFA you will have two key decisions to make:
-After you enable MFA you will also need to include MFA setup when users sign up. This will change depending on if you choose TOTP, SMS, or both. - -### Set up TOTP + -You can add Time-based One-time Password (TOTP) to your app which will ask users to complete authentication using a time-based one-time password (TOTP) after their username and password are verified. These TOTPs are generated using software token authentication apps like "Google Authenticator". When TOTP MFA is set up your user will be presented with a private key or QR code that they must enter into the TOTP-generating app. This app will then begin generating codes for the user to use for subsequent sign-in sessions. +When using Amplify CLI to set up backend resources, the following options are only available when starting a new project (via `amplify add auth`). You will not have access to these settings after creation (via `amplify update`). -You can set up TOTP for a user in your app with the `setupTOTPAuth` method. As part of this workflow you can also specify how users see the code retrieved from the authenticator app (e.g. numeric code or QR code), confirm the initial setup with the authenticator app, set TOTP as the preferred MFA method, and pass the TOTP code with the MFA type using the `confirmSignIn` method: + - + -```ts -import { CognitoUserSession } from 'amazon-cognito-identity-js'; -import { Auth } from 'aws-amplify'; +Run `amplify add auth` to create a new Cognito Auth resource, and follow the prompts below depending on how you want to integrate MFA into your flow. -type SetupTOTPAuthParameters = { - user: string; - challengeAnswer: string; - mfaType?: 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; -}; +Turning MFA "ON" will make it required for all users, while "Optional" will make it available to enable on a per-user basis. -export async function setupTOTPAuth({ user, challengeAnswer, mfaType }: SetupTOTPAuthParameters) { - // To set up TOTP, first you need to get a `authorization code` from Amazon Cognito. - // `user` is the current Authenticated user: - const secretCode = await Auth.setupTOTP(user); +#### SMS MFA - // You can directly display the `code` to the user or convert it to a QR code to be scanned. - // For example, use following code sample to render a QR code with `qrcode.react` component: - // import QRCodeCanvas from 'qrcode.react'; - // const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + secretCode + "&issuer=" + issuer; - // + - // ... +**Note:** If you create or update an SMS MFA configuration for your Cognito user pool, the Cognito service will send a test SMS message to an internal number in order to verify your configuration. You will be charged for these test messages by Amazon SNS. - // 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. - try { - const cognitoUserSession: CognitoUserSession = await Auth.verifyTotpToken( - user, - challengeAnswer - ); - // Don't forget to set TOTP as the preferred MFA method. - await Auth.setPreferredMFA(user, 'TOTP'); - } catch (error) { - // Token is not verified - } +Refer to [SMS sandbox](/lib/auth/sms_flows#sandbox-mode). For information about Amazon SNS pricing, see [Worldwide SMS Pricing](https://aws.amazon.com/sns/sms-pricing/). - // ... + - // Finally, when sign-in with MFA is enabled, use the `confirmSignIn` method - // to pass the TOTP code and MFA type. - const OTPCode = '123456'; // Code retrieved from authenticator app. - await Auth.confirmSignIn(user, OTPCode, mfaType); // Optional, MFA Type e.g. SMS_MFA || SOFTWARE_TOKEN_MFA -} +```bash +$ amplify add auth + +? Do you want to use the default authentication and security configuration? +# Manual configuration + +... Answer as appropriate + +? Multifactor authentication (MFA) user login options: +# ON (Required for all logins, can not be enabled later) +? For user login, select the MFA types: +# SMS Text Message +? Please specify an SMS authentication message: +# Your authentication code is {####} + +... Answer as appropriate + +Some next steps: +"amplify push" will build all your local backend resources and provision it in the cloud +"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud +``` + +#### TOTP MFA +```bash +$ amplify add auth + +? Do you want to use the default authentication and security configuration? +# Manual configuration + +... Answer as appropriate + +? Multifactor authentication (MFA) user login options: +# ON (Required for all logins, can not be enabled later) +? For user login, select the MFA types: +# Time-Based One-Time Password (TOTP) + +... Answer as appropriate + +Some next steps: +"amplify push" will build all your local backend resources and provision it in the cloud +"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud ``` - + -```js -import { Auth } from 'aws-amplify'; +Run `amplify update auth` and follow the prompts as guided below. -async function setupTOTPAuth(user, challengeAnswer, mfaType) { - // To set up TOTP, first you need to get a `authorization code` from Amazon Cognito. - // `user` is the current Authenticated user: - const OTPCode = '123456'; // Code retrieved from authenticator app. +The following steps show how to enable MFA as "Optional" for users. In this mode, MFA must be enabled on a user-by-user basis, either through an Admin SDK +(e.g. via a Lambda trigger as part of the sign-up process), or manually in the Cognito console. - // You can directly display the `code` to the user or convert it to a QR code to be scanned. - // For example, use following code sample to render a QR code with `qrcode.react` component: - // import QRCodeCanvas from 'qrcode.react'; - // const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + code + "&issuer=" + issuer; - // +If you'd like to make MFA required for users, you must first delete your auth resource by running `amplify remove auth`, then follow the **New Project** flow on this page. - // ... +#### SMS MFA - // 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. - try { - const cognitoUserSession = await Auth.verifyTotpToken(user, challengeAnswer); - // Don't forget to set TOTP as the preferred MFA method. - await Auth.setPreferredMFA(user, 'TOTP'); - } catch (error) { - // Token is not verified - } + - // ... +**Note:** If you create or update an SMS MFA configuration for your Cognito user pool, the Cognito service will send a test SMS message to an internal number in order to verify your configuration. You will be charged for these test messages by Amazon SNS. - // Finally, when sign-in with MFA is enabled, use the `confirmSignIn` method - // to pass the TOTP code and MFA type. - await Auth.confirmSignIn(user, code, mfaType); // Optional, MFA Type e.g. SMS_MFA || SOFTWARE_TOKEN_MFA -} +Refer to [SMS sandbox](/lib/auth/sms_flows#sandbox-mode). For information about Amazon SNS pricing, see [Worldwide SMS Pricing](https://aws.amazon.com/sns/sms-pricing/). + + + +```bash +$ amplify update auth + +? What do you want to do? +# Walkthrough all the auth configurations + +... Answer as appropriate + +? Multifactor authentication (MFA) user login options: +# OPTIONAL (Individual users can use MFA) +? For user login, select the MFA types: +# SMS Text Message +? Please specify an SMS authentication message: +# Your authentication code is {####} + +... Answer as appropriate + +Some next steps: +"amplify push" will build all your local backend resources and provision it in the cloud +"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud +``` + + +#### TOTP MFA +```bash +$ amplify update auth + +? What do you want to do? +# Walkthrough all the auth configurations + +... Answer as appropriate + +? Multifactor authentication (MFA) user login options: +# OPTIONAL (Individual users can use MFA) +? For user login, select the MFA types: +# Time-Based One-Time Password (TOTP) + +... Answer as appropriate + +Some next steps: +"amplify push" will build all your local backend resources and provision it in the cloud +"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud ``` + - +After you enable MFA you will also need to include MFA setup when users sign up. This will change depending on if you enable SMS, TOTP or both. -There are few limitations for TOTP MFA to keep in mind: -1. Amazon Cognito does not support hardware-based MFA. Use a software token MFA through an authenticator app that generates TOTP codes. -2. When TOTP is required your user must register with an authenticator app or subsequent sign-in attempts will fail. -3. Your users can use TOTP for MFA even if you disable TOTP for the user pool later. +### Set up Multi-factor authentication with SMS -To learn more details review the [*Amazon Cognito TOTP software token MFA*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-totp.html) documentation. +You can use Short Message Service (SMS) as a second layer of authentication with MFA. When SMS is enabled, your users will get an authentication code via a text message to complete sign-in after they sign in with their username and password. - +If you do not have one already, you will need to configure an IAM role to use with Amazon Simple Notification Service (Amazon SNS) to manage SMS messages. You will then add this role under the "Messaging" tab for your user pool in the Amazon Cognito console. For additional information see the [*Amazon Cognito SMS text message MFA*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-sms-text-message.html) documentation. -### Set up SMS +#### Enable SMS MFA during sign-up -You can also use Short Message Service (SMS) as a second layer of authentication with MFA. When SMS is enabled, your users will get an authentication code via a text message to complete sign-in after they sign in with their username and password. +You will need to pass `phone_number` as a user attribute to enable SMS MFA for your users during sign-up. However, if the primary sign-in mechanism for your Cognito resource is `phone_number` (without enabling `username`), then you do not need to pass it as an attribute. -After you enable MFA with Amazon Cognito, you will also need to configure an IAM role to use with Amazon Simple Notification Service (Amazon SNS) to manage SMS messages. You will then add this role under the "Messaging" tab for your user pool in the Amazon Cognito console. For additional information see the [*Amazon Cognito SMS text message MFA*](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-sms-text-message.html) documentation. +```javascript +Auth.signUp({ + username, + password, + attributes: { + phone_number: '+15558675309' // Replace with a valid phone number + } +}); +``` - +By default, you have to verify a user account after they sign up using the `confirmSignUp` API, which will send a one-time password to the user's phone number or email, depending on your Amazon Cognito configuration. -**Note:** If you create or update an SMS MFA configuration for your Cognito user pool, the Cognito service will send a test SMS message to an internal number in order to verify your configuration. You will be charged for these test messages by Amazon SNS. +```javascript +import { Auth } from 'aws-amplify'; + +async function confirmSignUp() { + try { + await Auth.confirmSignUp(username, code); + } catch (error) { + console.log('error confirming sign up', error); + } +} +``` -For information about Amazon SNS pricing, see [Worldwide SMS Pricing](https://aws.amazon.com/sns/sms-pricing/). +#### Manage SMS MFA during sign-in - +After a user signs in, if they have MFA enabled for their account, a challenge will be returned that needs to call the `confirmSignIn` API where the user provides their confirmation code sent to their phone number. Amplify will then verify with Cognito that the SMS code is valid and complete the sign-in process by returning access, ID, and refresh tokens that are all handled by Amplify internally. Once the user completes the SMS text message flow their phone number is marked as verified in your user pool. -You will then want to update your app UI to prompt your users to enter their phone number to receive SMS codes. Then, when a user signs in, Amazon Cognito responds with a challenge that requires the user to provide an SMS verification code. This is where you can trigger `Auth.confirmSignIn()` and pass in the code provided by the user. Amplify will then verify with Cognito that the SMS code is valid and complete the sign-in process by returning access, ID, and refresh tokens that are all handled by Amplify internally. Once the user completes the SMS text message flow their phone number is marked as verified in your user pool. +In the example below you will see that because MFA is "ON" or enabled as an option for the user, you must call `confirmSignIn` with the OTP sent to their phone. After a user has been signed in, you can call `updateMFAPreference` to record the MFA type as enabled for the user and optionally set it as preferred so that subsequent logins default to using this MFA type. @@ -166,7 +224,7 @@ type ConfirmSignInWithMFAParameters = { password: string; }; -type MFAType = 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; +type MFAType = 'SMS_MFA'; export async function signInWithMFA({ username, password }: ConfirmSignInWithMFAParameters) { try { @@ -235,16 +293,140 @@ async function signInWithMFA() { -### Set up MFA preferred type +### Set up Multi-factor authentication with TOTP + +You can use Time-based One-Time Password (TOTP) for multi-factor authentication (MFA) in your web or mobile applications. The Amplify Auth category includes support for TOTP setup and verification using authenticator apps, offering an integrated solution and enhanced security for your users. These apps, such as Google Authenticator or Microsoft Authenticator, have the TOTP algorithm built-in and work by using a shared secret key and the current time to generate short-lived, six digit passwords. + +#### Enable TOTP for your users -Both TOTP MFA and SMS MFA methods are supported by Amazon Cognito. If you provide the option for your users to choose their second authentication factor or opt out, then you will want to also save that preference for future sessions with the `setupMFAType` method: +After you initiate a user sign-in with the `signIn` API where your user is required to set up TOTP as an MFA method, the API call will return `setupTOTPAuth` as a challenge and next step to handle in your app. You will get that challenge if the following conditions are met: + +- MFA is marked as "Required" in Cognito User Pool. +- TOTP is enabled in the Cognito User Pool +- User does not have TOTP MFA set up already. + +You can set up TOTP for a user in your app with the `setupTOTPAuth` API. As part of this workflow you can also specify how users see the code retrieved from the authenticator app (e.g. numeric code or QR code), confirm the initial setup with the authenticator app, set TOTP as the preferred MFA method, and pass the TOTP code with the MFA type using the `confirmSignIn` API: ```ts +import { CognitoUserSession } from 'amazon-cognito-identity-js'; import { Auth } from 'aws-amplify'; +type SetupTOTPAuthParameters = { + user: string; + challengeAnswer: string; + mfaType?: 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; +}; + +export async function setupTOTPAuth({ user, challengeAnswer, mfaType }: SetupTOTPAuthParameters) { + // To set up TOTP, first you need to get a `authorization code` from Amazon Cognito. + // `user` is the current Authenticated user: + const secretCode = await Auth.setupTOTP(user); + + // You can directly display the `code` to the user or convert it to a QR code to be scanned. + // For example, use following code sample to render a QR code with `qrcode.react` component: + // import QRCodeCanvas from 'qrcode.react'; + // const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + secretCode + "&issuer=" + issuer; + // + + // ... + + // 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. + try { + const cognitoUserSession: CognitoUserSession = await Auth.verifyTotpToken( + user, + challengeAnswer + ); + // Don't forget to set TOTP as the preferred MFA method. + await Auth.setPreferredMFA(user, 'TOTP'); + } catch (error) { + // Token is not verified + } + + // ... + + // Finally, when sign-in with MFA is enabled, use the `confirmSignIn` API + // to pass the TOTP code and MFA type. + const OTPCode = '123456'; // Code retrieved from authenticator app. + await Auth.confirmSignIn(user, OTPCode, mfaType); // Optional, MFA Type e.g. SMS_MFA || SOFTWARE_TOKEN_MFA +} +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function setupTOTPAuth(user, challengeAnswer, mfaType) { + // To set up TOTP, first you need to get a `authorization code` from Amazon Cognito. + // `user` is the current Authenticated user: + const OTPCode = '123456'; // Code retrieved from authenticator app. + + // You can directly display the `code` to the user or convert it to a QR code to be scanned. + // For example, use following code sample to render a QR code with `qrcode.react` component: + // import QRCodeCanvas from 'qrcode.react'; + // const str = "otpauth://totp/AWSCognito:"+ username + "?secret=" + code + "&issuer=" + issuer; + // + + // ... + + // 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. + try { + const cognitoUserSession = await Auth.verifyTotpToken(user, challengeAnswer); + // Don't forget to set TOTP as the preferred MFA method. + await Auth.setPreferredMFA(user, 'TOTP'); + } catch (error) { + // Token is not verified + } + + // ... + + // Finally, when sign-in with MFA is enabled, use the `confirmSignIn` API + // to pass the TOTP code and MFA type. + await Auth.confirmSignIn(user, code, mfaType); // Optional, MFA Type e.g. SMS_MFA || SOFTWARE_TOKEN_MFA +} +``` + + + +Once the authenticator app is set up, the user can generate a TOTP code and provide it to the library to complete the sign in process. + + + +TOTP MFA can be set up after a user has signed in. This can be done when the following conditions are met: + +- MFA is marked as "Optional" or "Required" in the Cognito User Pool +- TOTP is marked as an enabled MFA method in Cognito user pool + +TOTP can be set up by calling the `setupTOTPAuth` and `verifyTotpToken` APIs in the `Auth` category. + +Invoke the `setupTOTPAuth` API to generate a `SetupTOTPAuthParameters` object which should be used to configure an Authenticator app like Microsoft Authenticator or Google Authenticator. For more advanced use cases, `SetupTOTPAuthParameters` also contains a `secretCode` which can be used to either generate a QR code or be manually entered into an Authenticator app. Once the Authenticator app is set up, the user must generate a TOTP code and provide it to the library. Pass the code to `verifyTotpToken` to complete the TOTP setup process. + + + +#### Recover from a lost TOTP device + + + +If a user loses access to their TOTP device, they will need to contact an administrator to get help accessing to their account. Based on the Cognito User Pool configuration, the administrator can use the [AdminSetUserMFAPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserMFAPreference.html) to either change the MFA preference to a different MFA method or to disable MFA for the user. + + + +In a scenario where MFA is marked as "Required" in Cognito User Pool and another MFA method is not set up, the administrator would need to first initiate an [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) call and update the user’s phone number attribute. Once this is complete, the administrator can continue changing the MFA preference to SMS as suggested above. + +### Set up a user's preferred MFA method + +Since both SMS MFA and TOTP MFA methods are supported by Amazon Cognito, you can provide the option for your users to choose their second authentication factor or opt out. When both are available you will need to also save their preference for future sessions with the `setupMFAType` API: + + + + +```ts +import { Auth } from 'aws-amplify'; export async function setupMFAType() { // You can select preferred mfa type, for example: @@ -301,7 +483,6 @@ Once the preferred MFA method is set for your user you will then want to use the ```ts import { Auth } from 'aws-amplify'; - export async function getPreferredMFAType() { try { // Will retrieve the current mfa type from cache @@ -342,212 +523,10 @@ try { -To avoid unexpected responses from Cognito, it is recommended to call `Auth.setPreferredMFA()` to ensure a user has set their MFA method *before* retrieving MFA settings with `Auth.getPreferredMFA()`. +Only one MFA method can be marked as preferred at a time. If the user has multiple MFA methods enabled and tries to mark more than one MFA method as preferred, the API will throw an error. To avoid unexpected responses from Cognito, it is recommended to call `Auth.setPreferredMFA()` to ensure a user has set their MFA method *before* retrieving MFA settings with `Auth.getPreferredMFA()`. - - -When signing in with user name and password, your user will either sign in directly or be asked to pass challenges to be authenticated. The `user` object returned from `Auth.signIn` will contain `challengeName` and `challengeParam` if the user needs to pass those challenges. You can call corresponding functions based on these two parameters. - -Challenge Name: - -- `SMS_MFA`: The user needs to input the code received from SMS message. You can submit the code by `Auth.confirmSignIn`. -- `SOFTWARE_TOKEN_MFA`: The user needs to input the OTP(one time password). You can submit the code by `Auth.confirmSignIn`. -- `NEW_PASSWORD_REQUIRED`: This happens when the user account is created through the Cognito console. The user needs to input the new password and required attributes. You can submit those data by `Auth.completeNewPassword`. -- `MFA_SETUP`: This happens when the MFA method is TOTP (time-based one time password) which requires the user to go through additional steps to generate passwords with an Authenticator app. You can start the setup process using `setupTOTPAuth`. -- `SELECT_MFA_TYPE`: This happens when both SMS and TOTP methods are enabled but neither is set as preferred. You can set up your frontend application to let users choose what type they want to use in the current session and set it using the `user.sendMFASelectionAnswer` function. - -The following code is only to demonstrate these options: - - - - -```ts -import { Auth } from 'aws-amplify'; - -type SignInParameters = { - username: string; - password: string; - mfaType?: 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA'; -}; - -type UserInput = { - username: string; - email: string; - phone_number: string; -}; - -export async function signIn({ username, password, mfaType }: SignInParameters) { - try { - const user = await Auth.signIn(username, password); - if (user?.challengeName === 'SMS_MFA' || user?.challengeName === 'SOFTWARE_TOKEN_MFA') { - // You need to get the code from the UI inputs - // and then trigger the following function with a button click - const code: string = await getCodeFromUserInput(); - // If MFA is enabled, sign-in should be confirmed with the confirmation code - const loggedUser = await Auth.confirmSignIn( - user, // Return object from Auth.signIn() - code, // Confirmation code - mfaType // MFA Type e.g. SMS_MFA, SOFTWARE_TOKEN_MFA - ); - } else if (user?.challengeName === 'NEW_PASSWORD_REQUIRED') { - const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number'] - // You need to get the new password and required attributes from the UI inputs - // and then trigger the following function with a button click - // For example, the email and phone_number are required attributes - const { username, email, phone_number }: UserInput = - await getInfoFromUserInput(); - const loggedUser = await Auth.completeNewPassword( - user, // the Cognito User Object - newPassword, // the new password - // OPTIONAL, the required attributes - { - email, - phone_number, - } - ); - } else if (user?.challengeName === 'MFA_SETUP') { - // This happens when the MFA method is TOTP - // The user needs to setup the TOTP before using it - // More info please check the Enabling MFA part - await Auth.setupTOTP(user); - } else if (user?.challengeName === 'SELECT_MFA_TYPE') { - // You need to get the MFA method (SMS or TOTP) from user - // and trigger the following function - // user object needs to be CognitoUser type - user.sendMFASelectionAnswer(mfaType, { - onFailure: (err: Error) => { - console.error(err); - }, - mfaRequired: (challengeName, parameters) => { - // Auth.confirmSignIn with SMS code - }, - totpRequired: (challengeName, parameters) => { - // Auth.confirmSignIn with TOTP code - }, - }); - } else { - // The user directly signs in - console.log(user); - } - } catch (err) { - if (err?.code === 'UserNotConfirmedException') { - // The error happens if the user didn't finish the confirmation step when signing up - // In this case you need to resend the code and confirm the user - // About how to resend the code and confirm the user, please check the signUp part - } else if (err?.code === 'PasswordResetRequiredException') { - // The error happens when the password is reset in the Cognito console - // In this case you need to call forgotPassword to reset the password - // Please check the Forgot Password part. - } else if (err?.code === 'NotAuthorizedException') { - // The error happens when the incorrect password is provided - } else if (err?.code === 'UserNotFoundException') { - // The error happens when the supplied username/email does not exist in the Cognito user pool - } else { - console.log(err); - } - } -} - -async function getCodeFromUserInput(): Promise { - // fetch code using a user form input -} -async function getInfoFromUserInput(): Promise { - // fetch user inputs like username, email and phoneNumber -} -``` - - - -```js -import { Auth } from 'aws-amplify'; - -async function signIn() { - try { - const user = await Auth.signIn(username, password); - if (user?.challengeName === 'SMS_MFA' || user?.challengeName === 'SOFTWARE_TOKEN_MFA') { - // You need to get the code from the UI inputs - // and then trigger the following function with a button click - const code = await getCodeFromUserInput(); - // If MFA is enabled, sign-in should be confirmed with the confirmation code - const loggedUser = await Auth.confirmSignIn( - user, // Return object from Auth.signIn() - code, // Confirmation code - mfaType // MFA Type e.g. SMS_MFA, SOFTWARE_TOKEN_MFA - ); - } else if (user?.challengeName === 'NEW_PASSWORD_REQUIRED') { - const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number'] - // You need to get the new password and required attributes from the UI inputs - // and then trigger the following function with a button click - // For example, the email and phone_number are required attributes - const { username, email, phone_number } = await getInfoFromUserInput(); - const loggedUser = await Auth.completeNewPassword( - user, // the Cognito User Object - newPassword, // the new password - // OPTIONAL, the required attributes - { - email, // from user input - phone_number, // from user input - } - ); - } else if (user?.challengeName === 'MFA_SETUP') { - // This happens when the MFA method is TOTP - // The user needs to setup the TOTP before using it - // More info please check the Enabling MFA part - await Auth.setupTOTP(user); - } else if (user?.challengeName === 'SELECT_MFA_TYPE') { - // You need to get the MFA method (SMS or TOTP) from user - // and trigger the following function - // user object needs to be CognitoUser type - user.sendMFASelectionAnswer(mfaType, { - onFailure: (err) => { - console.error(err); - }, - mfaRequired: (challengeName, parameters) => { - // Auth.confirmSignIn with SMS code - }, - totpRequired: (challengeName, parameters) => { - // Auth.confirmSignIn with TOTP code - }, - }); - } else { - // The user directly signs in - console.log(user); - } - } catch (err) { - if (err?.code === 'UserNotConfirmedException') { - // The error happens if the user didn't finish the confirmation step when signing up - // In this case you need to resend the code and confirm the user - // About how to resend the code and confirm the user, please check the signUp part - } else if (err?.code === 'PasswordResetRequiredException') { - // The error happens when the password is reset in the Cognito console - // In this case you need to call forgotPassword to reset the password - // Please check the Forgot Password part. - } else if (err?.code === 'NotAuthorizedException') { - // The error happens when the incorrect password is provided - } else if (err?.code === 'UserNotFoundException') { - // The error happens when the supplied username/email does not exist in the Cognito user pool - } else { - console.log(err); - } - } -} - -async function getCodeFromUserInput() { - // fetch code using a user form input -} -async function getInfoFromUserInput() { - // fetch user inputs like username, email and phoneNumber -} -``` - - - - - -
- You can now enable multi-factor authentication and specify your second authentication method with TOTP or SMS. Your users can set their preferred method and you can retrieve this for them when they sign in. You can now look to add features like remembering a device to reduce friction in the sign-in workflow. ## Remember a device @@ -560,7 +539,7 @@ Remembering a device is useful in conjunction with MFA because it allows the sec -### Configure the Amplify Auth Category +### Configure device tracking You can enable the remembered device functionality in the Cognito User Pool console. To begin, go to your project directory and issue the command: @@ -635,7 +614,7 @@ async function rememberDevice() {
-### Forget devices +#### Forget devices You can also forget devices but note that forgotten devices are still tracked. @@ -670,7 +649,7 @@ async function forgetDevice() { -### Fetch devices +#### Fetch devices You can fetch a list of remembered devices by using the following: From 9fca887cd32de5621e254eb0cc215dc1d31bd2d2 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Tue, 12 Sep 2023 14:24:31 -0700 Subject: [PATCH 005/164] Update based on API ref --- src/pages/lib/auth/mfa/q/platform/[platform].mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pages/lib/auth/mfa/q/platform/[platform].mdx b/src/pages/lib/auth/mfa/q/platform/[platform].mdx index 4381972d141..7610f711789 100644 --- a/src/pages/lib/auth/mfa/q/platform/[platform].mdx +++ b/src/pages/lib/auth/mfa/q/platform/[platform].mdx @@ -211,7 +211,7 @@ async function confirmSignUp() { After a user signs in, if they have MFA enabled for their account, a challenge will be returned that needs to call the `confirmSignIn` API where the user provides their confirmation code sent to their phone number. Amplify will then verify with Cognito that the SMS code is valid and complete the sign-in process by returning access, ID, and refresh tokens that are all handled by Amplify internally. Once the user completes the SMS text message flow their phone number is marked as verified in your user pool. -In the example below you will see that because MFA is "ON" or enabled as an option for the user, you must call `confirmSignIn` with the OTP sent to their phone. After a user has been signed in, you can call `updateMFAPreference` to record the MFA type as enabled for the user and optionally set it as preferred so that subsequent logins default to using this MFA type. +In the example below you will see that because MFA is "ON" or enabled as an option for the user, you must call `confirmSignIn` with the OTP sent to their phone. After a user has been signed in, you can call `setPreferredMFA` to record the MFA type as enabled for the user and set it as preferred so that subsequent logins default to using this MFA type. @@ -299,13 +299,13 @@ You can use Time-based One-Time Password (TOTP) for multi-factor authentication #### Enable TOTP for your users -After you initiate a user sign-in with the `signIn` API where your user is required to set up TOTP as an MFA method, the API call will return `setupTOTPAuth` as a challenge and next step to handle in your app. You will get that challenge if the following conditions are met: +After you initiate a user sign-in with the `signIn` API where your user is required to set up TOTP as an MFA method, the API call will return `setupTOTP` as a challenge and next step to handle in your app. You will get that challenge if the following conditions are met: - MFA is marked as "Required" in Cognito User Pool. - TOTP is enabled in the Cognito User Pool - User does not have TOTP MFA set up already. -You can set up TOTP for a user in your app with the `setupTOTPAuth` API. As part of this workflow you can also specify how users see the code retrieved from the authenticator app (e.g. numeric code or QR code), confirm the initial setup with the authenticator app, set TOTP as the preferred MFA method, and pass the TOTP code with the MFA type using the `confirmSignIn` API: +You can set up TOTP for a user in your app with the `setupTOTP` API. As part of this workflow you can also specify how users see the code retrieved from the authenticator app (e.g. numeric code or QR code), confirm the initial setup with the authenticator app, set TOTP as the preferred MFA method, and pass the TOTP code with the MFA type using the `confirmSignIn` API: @@ -402,9 +402,9 @@ TOTP MFA can be set up after a user has signed in. This can be done when the fol - MFA is marked as "Optional" or "Required" in the Cognito User Pool - TOTP is marked as an enabled MFA method in Cognito user pool -TOTP can be set up by calling the `setupTOTPAuth` and `verifyTotpToken` APIs in the `Auth` category. +TOTP can be set up by calling the `setupTOTP` and `verifyTotpToken` APIs in the `Auth` category. -Invoke the `setupTOTPAuth` API to generate a `SetupTOTPAuthParameters` object which should be used to configure an Authenticator app like Microsoft Authenticator or Google Authenticator. For more advanced use cases, `SetupTOTPAuthParameters` also contains a `secretCode` which can be used to either generate a QR code or be manually entered into an Authenticator app. Once the Authenticator app is set up, the user must generate a TOTP code and provide it to the library. Pass the code to `verifyTotpToken` to complete the TOTP setup process. +Invoke the `setupTOTP` API to generate a `SetupTOTPAuthParameters` object which should be used to configure an Authenticator app like Microsoft Authenticator or Google Authenticator. For more advanced use cases, `SetupTOTPAuthParameters` also contains a `secretCode` which can be used to either generate a QR code or be manually entered into an Authenticator app. Once the Authenticator app is set up, the user must generate a TOTP code and provide it to the library. Pass the code to `verifyTotpToken` to complete the TOTP setup process.
From b29ea207d71f68b159a3ed5e1deccc4ea5bec56c Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Wed, 13 Sep 2023 18:59:56 -0700 Subject: [PATCH 006/164] Updating directory for new page --- src/directory/directory.mjs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index fed0d273e7a..62800978471 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -267,6 +267,11 @@ export const directory = { route: '/lib/auth/getting-started', filters: ['android', 'flutter', 'ios', 'js', 'react-native'] }, + { + title: 'Manage user session and credentials', + route: '/lib/auth/manage-session', + filters: ['js'] + }, { title: 'Enable sign-up, sign-in, and sign-out', route: '/lib/auth/emailpassword', From 33b0cd4743463006e2344844dd8ffb5444f9926a Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Wed, 13 Sep 2023 19:04:52 -0700 Subject: [PATCH 007/164] Adding new page for managing user sessions --- .../manage-session/q/platform/[platform].mdx | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 src/pages/lib/auth/manage-session/q/platform/[platform].mdx diff --git a/src/pages/lib/auth/manage-session/q/platform/[platform].mdx b/src/pages/lib/auth/manage-session/q/platform/[platform].mdx new file mode 100644 index 00000000000..66a747f1f92 --- /dev/null +++ b/src/pages/lib/auth/manage-session/q/platform/[platform].mdx @@ -0,0 +1,209 @@ +export const meta = { + title: `Manage user session and credentials`, + description: `Learn how to manage user sessions and credentials.`, +}; + + + +[comment]: # (source content from lib/auth/manageusers/q/platform/js/#retrieve-current-session ; src/fragments/lib/auth/js/manageusers.mdx) + +Amplify Auth provides access to current user sessions and tokens to help you retrieve your customer's information to determine if they are logged in with a valid session and control their access to your app. You can manage tokens and expiration times and revoke sessions. In this guide we will review how to retrieve your user’s session and understand what token management options are available. + +Before you begin you will need: +- Sign-up set up +- A test user signed in + +## Retrieve my current authenticated user + +You can use the `Auth.currentAuthenticatedUser()` API which returns the full `CognitoUser` object. This object contains information about the currently authenticated user including the session and user attributes. + +To call `Auth.currentAuthenticatedUser()` to get the current authenticated user object: + + + + +```ts +import { Auth } from 'aws-amplify'; + +async function currentAuthenticatedUser() { + try { + const user = await Auth.currentAuthenticatedUser({ + bypassCache: false // Optional, By default is false. If set to true, this call + // will send a request to Cognito to get the latest user data. + }); + console.log(user); + } catch(err) { + console.log(err); + } +}; +``` + + + +```javascript +import { Auth } from 'aws-amplify'; + +async function currentAuthenticatedUser() { + try { + const user = Auth.currentAuthenticatedUser({ + bypassCache: false // Optional, By default is false. If set to true, this call + // will send a request to Cognito to get the latest user data. + }); + } catch(err) { + console.log(err); + } +}; +``` + + + +This method can be used to check if a user is signed in when the page is loaded. It will throw an error if there is no user signed in. This method should be called after the `Auth` module is configured or the user is signed in. To ensure that you can listen on the auth events `configured` or `signIn`. [Learn how to listen on auth events.](/lib/utilities/hub#authentication-events) + +## Retrieve my user’s session + +If you only need the session details you can use `Auth.currentSession()` which returns a `CognitoUserSession` object which contains the JWT (JSON Web Token). Credentials are exchanged for temporary access tokens when your users sign in. You can access these tokens to get user information to validate user access or perform actions unique to that user. + + + +This secure information in the `CognitoUserSession` object includes: +- `idToken` - A JWT that contains user identity information like username and email. It is used to authenticate the user. +- `accessToken` - A JWT used to access protected AWS resources and APIs. It contains the authorized scope. +- `refreshToken` - This a longer-lived token used to refresh expired access tokens by generating new ID and access tokens. +- `expiresIn` - Identifies token expiration time in seconds. + +Amazon Cognito tokens work by generating temporary access and ID tokens with an expiration time at user sign-in. The tokens are validated against the user pool to authorize access until they expire. + + + +
+ + + +**Note:** This method will automatically refresh the `accessToken` and `idToken` if tokens are expired and a valid `refreshToken` presented. So you can use this method to refresh the session if needed. + + + + + + +```ts +import { Auth } from 'aws-amplify'; + +Auth.currentSession() + .then((session) => { + const { accessToken, idToken, refreshToken } = session; + // Use the tokens to call AWS services + }) + .catch((err) => console.log(err)); +``` + + + + +```javascript +import { Auth } from 'aws-amplify'; + +async function currentSession() { + try { + const data = await Auth.currentSession(); + console.log(data); + } catch(err) { + console.log(err); + } +}; +``` + + + + +## Understand token management options + +Token keys are automatically rotated for you for added security but you can update how they are stored, customize the refresh rate and expiration times, and revoke tokens on sign out. + +### Update your token-saving mechanism + +You can update the storage mechanism to choose where and how tokens are persisted in your application. The default `BrowserLocalStorage` is suitable for most use cases, but you may want to use a different option for security or user experience reasons. + +#### Browser Local Storage + +In Amplify the `BrowserLocalStorage` is the default storage mechanism. It saves the tokens in the browser's `localStorage`. This local storage will persist across browser sessions and tabs. You can update to this storage by calling: + +```javascript +Auth.configure({ + storage: Auth.storage.BrowserLocalStorage +}); +``` + +#### Browser Session Storage + +`BrowserSessionStorage` saves the tokens in the browser's `sessionStorage` and these tokens will clear when a tab is closed. The benefit to this storage mechanism is that the session only lasts as long as the browser is open and you can sign out users when they close the tab. You can update to this storage by calling: + +```javascript +Auth.configure({ + storage: Auth.storage.BrowserSessionStorage +}); +``` + +#### Memory + +`Memory` stores the tokens in memory only. These tokens will be lost when the page is refreshed. You can update to this storage by calling: + +```javascript +Auth.configure({ + storage: Auth.storage.Memory +}); +``` + +#### Custom Storage + +You can implement your own custom storage mechanism by creating a class that implements the storage interface. Then update to use your custom storage by calling: + +```javascript +Auth.configure({ + storage: MyCustomStorage +}); +``` + +When you get the current user session, the tokens will be saved in your custom location. + +### Update token refresh duration and expiration + +You can set expiration and refresh rates for a user session tokens with Amplify Auth using the `setSignInUserSessionData` method. Shorter sessions will provide better security as it limits the window for subsequent API calls after a user signs out. Setting these values also allows you to customize the user experience for your app by controlling how often a user has to re-authenticate. + +For example, to set a session expiration of 1 hour (3600 seconds) and a refresh interval of 30 minutes (1800 seconds), you would: + +```javascript +Auth.setSignInUserSessionData({ + expiresIn: 3600, // Session expiration in seconds + refreshInterval: 1800 // Session refresh interval in seconds +}); +``` + +This will set the expiration and refresh behavior for the current authenticated user's session. The `expiresIn` value determines how long the session will last before the user has to sign in again. The `refreshInterval` value determines how often the session will be automatically refreshed with new access and ID tokens. By default, the session is refreshed 15 minutes before expiration. + + + +**Note:** You can also update token expiration times in the Amazon Cognito User Pool settings. Set the token expiration time in the Cognito User Pools console under "App integration" > "App client" settings. + + + +### Revoke tokens + +You can enable token revocation in Amazon Cognito. This will revoke refresh and access tokens when a user signs out, preventing them from being used to generate new tokens. Token revocation is enabled by default in new Cognito User Pools, but must be enabled for existing pools. + +Additionally, if you set up global sign-out with `Auth.signOut({ global: true })` to globally sign out your users, this will revoke all refresh and access tokens, invalidating them immediately. + +You can now change the user experience for your app by updating how and where your tokens are saved and managed. + +## Conclusion + +Congratulations! You finished the **Manage user session and credentials** guide. In this guide, you learned how to retrieve you current authenticated user, the user's session details, and reviewed several ways you can manage these user credentials. + +## Next steps + +Now that you updated how your credentials are managed you may also want to further refine the sing-in and sign-out workflows as well as update how you listen for these Auth events. We recommend you learn more about: + +- [Enable sign-up, sign-in, and sign-out](/lib/auth/emailpassword/q/platform/js/) +- [Auth events](/lib/auth/auth-events/q/platform/js/) + +
From 39558ef789e9934e268f4931e445b073d6c5aa52 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Thu, 14 Sep 2023 17:45:36 -0700 Subject: [PATCH 008/164] Updating the directory with new page title --- src/directory/directory.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index fed0d273e7a..656936c7367 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -273,7 +273,7 @@ export const directory = { filters: ['js', 'react-native'] }, { - title: 'Social sign-in (OAuth)', + title: 'Add social provider sign-in', route: '/lib/auth/social', filters: ['js', 'react-native'] }, From ba71788eb759db71d12b9691a6be4cb3fe6f54c3 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Thu, 14 Sep 2023 17:51:56 -0700 Subject: [PATCH 009/164] First half of updates to social sign-in --- .../lib/auth/social/q/platform/[platform].mdx | 689 +++++++++++++++++- 1 file changed, 686 insertions(+), 3 deletions(-) diff --git a/src/pages/lib/auth/social/q/platform/[platform].mdx b/src/pages/lib/auth/social/q/platform/[platform].mdx index 747ea2b6b54..51340c2314e 100644 --- a/src/pages/lib/auth/social/q/platform/[platform].mdx +++ b/src/pages/lib/auth/social/q/platform/[platform].mdx @@ -1,11 +1,694 @@ export const meta = { - title: `Social sign-in (OAuth)`, + title: `Add social provider sign-in`, description: `Learn how to setup social sign-in providers like Facebook, Google, Amazon, or Sign in with Apple.`, }; -import js0 from "/src/fragments/lib/auth/js/social.mdx"; + - +[comment]: # (source content from src/fragments/lib/auth/js/social.mdx ; src/fragments/lib/auth/common/setup_auth_provider.mdx ; src/fragments/lib/auth/common/configure_auth_category.mdx ; /src/fragments/cli/lambda_triggers_callout.mdx) + +You can enable your users to sign-in and authenticate with your application using their existing accounts with social providers like Apple, Amazon, Facebook, and Google. Once you configure your backend resources, you can use Authenticator or the Amplify Libraries to sign in users for that provider. This process will securely exchange credentials and gather user information. This information can then be used to create a new user in your app or link the social account to an existing user. Incorporating social provider sign-in provides your users with a streamlined registration, more sign-in options, and an integrated experience across their existing accounts and your application. + +In this guide we will review how you can add sign-in with social providers after you set up and configure your developer account with the provider. After this is set up you can use Authenticator or the Amplify Libraries to configure your Auth category and integrate with your app. + +Before you begin you will need: +- An Amplify project +- The Amplify libraries installed and configured + +## Set up your social auth provider + +Before you configure social sign-in with Amplify Auth you will need to set up your developer account with each provider you are using. + + + +[OAuth 2.0](https://en.wikipedia.org/wiki/OAuth) is the common Authorization framework used by web and mobile applications for accessing user information ("scopes") in a limited manner. Common analogies you will hear in OAuth is that of boarding a plane or staying in a hotel - showing your identification is the authentication piece (signing into an app) and using the boarding pass/hotel key is what you are authorized to access. + +OAuth support in Amplify uses Cognito User Pools and supports federation with social providers, which will automatically create a corresponding user in the User Pool after a login. [OIDC](https://en.wikipedia.org/wiki/OpenID_Connect) tokens are available in the app after the application has completed this process. + + + +
+ + + + +1. Create a [developer account with Facebook](https://developers.facebook.com/docs/facebook-login). + +2. [Sign in](https://developers.facebook.com/) with your Facebook credentials. + +3. Choose *My Apps* from the top navigation bar, and on the page that loads choose *Create App*. +![Create App button in the My Apps page of the Facebook developer account.](/images/cognitoHostedUI/facebook1.png) + +4. For your use case, choose *Set up Facebook Login*. +![Set up Facebook Login option selected from list.](/images/cognitoHostedUI/facebook2.png) + +5. For platform, choose *Website* and select *No, I'm not building a game*. + +6. Give your Facebook app a name and choose *Create app*. +![Form fields for the Facebook create app form.](/images/cognitoHostedUI/facebook3.png) + +7. On the left navigation bar, choose *Settings* and then *Basic*. +![App ID and App Secret in the basic settings tab of the dashboard.](/images/cognitoHostedUI/facebook4.png) + +8. Note the *App ID* and the *App Secret*. You will use them in the next section during the CLI flow. + + + + +1. Go to [Google developer console](https://console.developers.google.com). + +2. Click *Select a project*. +![Select a project button on the nav bar is circled.](/images/cognitoHostedUI/google1.png) + +3. Click *NEW PROJECT*. +![The new project button is circled on the select a project popup.](/images/cognitoHostedUI/google2.png) + +4. Type in project name and click *CREATE*. +![The create button is circled in the new project page.](/images/cognitoHostedUI/google3.png) + +5. Once the project is created, from the left *Navigation menu*, select *APIs & Services*, then select *Credentials*. +![The top left menu icon is selected, then the APIs and services option, then the credentials option.](/images/cognitoHostedUI/google4.png) + +6. Click *CONFIGURE CONSENT SCREEN*. +![The configure consent screen button is circled in the oauth consent screen section.](/images/cognitoHostedUI/google5.png) + +7. Click *CREATE*. +![The create button is circled in the OAuth consent screen section.](/images/cognitoHostedUI/google6.png) + +8. Type in *App Information* and *Developer contact information* which are required field and click *SAVE AND CONTINUE* three times (OAuth consent screen -> Scopes -> Test Users) to finish setting up consent screen. + +9. Back under the *Credentials* tab, Create your OAuth2.0 credentials by choosing *OAuth client ID* from the *Create credentials* drop-down list. +![The Create credentials button is circled, then the oauth client ID button is circled in the credentials section.](/images/cognitoHostedUI/google7.png). + +10. Choose *Web application* as *Application type* and name your OAuth Client. + +11. Click *Create*. + +12. Take note of *Your client ID* and *Your Client Secret*. You will need them for the next section in the CLI flow. + +13. Choose *OK*. + + + + +1. Create a [developer account with Amazon](https://developer.amazon.com/login-with-amazon). + +2. [Sign in](https://developer.amazon.com/loginwithamazon/console/site/lwa/overview.html) with your Amazon credentials. + +3. You need to create an Amazon security profile to receive the Amazon client ID and client secret. Choose *Create a Security Profile*. +![The login with Amazon console with a create a new security profile button displayed.](/images/cognitoHostedUI/amazon1.png) + +4. Type in a *Security Profile Name*, a *Security Profile Description*, and a *Consent Privacy Notice URL*. +![Security profile management page with steps to fill out a form for the new security profile.](/images/cognitoHostedUI/amazon2.png) + +5. Choose *Save*. + +6. Choose *Show Client ID and Client Secret* to show the client ID and secret. You will need them for the next section in the CLI flow. +![Choosing client ID and client secret.](/images/cognitoHostedUI/amazon3.png) + + + + + +1. [Sign In](https://developer.apple.com/account/) with your Apple developer credentials. + +2. On the main developer portal page, select *Certificates, IDs, & Profiles*. + +3. On the left navigation bar, select *Identifier*. + +4. On the Identifiers page, select the *+* icon. + +5. On the *Register a New Identifier* page, select *App IDs*. + +6. On the *Register an App ID* page, under *App ID Prefix*, take note of the *Team ID* value. + +7. Provide a description in the *Description* text box and provide the `bundleID` of the iOS app. +![Register an App ID in the certificates, identifiers and profiles section.](/images/cognitoHostedUI/apple1.png) + +8. Under *Capabilities*, select *Sign in with Apple*. + +9. Select *Continue*, review the configuration, and then select *Register*. + +10. On the *Identifiers* page, on the right, select *App IDs*, and then select *Services ID*. + +11. Select the *+* icon and, on the *Register a New Identifier* page, select *Services IDs*. + +12. Provide a description in the *Description* text box and provide an identifier for the service ID. +![Register a services ID in the certificates, identifiers and profiles section.](/images/cognitoHostedUI/apple2.png) + +13. Select *Continue* and register the service ID. + + + + +Your developer accounts with the social providers are now set up and you can return to your Auth project for next steps. + +## Configure the Auth category + +Once you have the social providers configured you can update your Auth configuration through the Amplify CLI or use the out-of-box set up through [Authenticator](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#social-providers). The steps below outline using the CLI. + + + + When configuring social sign-in through the Amplify CLI, it's important to exercise caution when designating attributes as "required". Each social identity provider has different information they send back to Cognito. User Pool attributes that are initially set up as "required" cannot be changed later. You may have to migrate the users or create a new User Pool if you need to change requirements. + + + +To begin with the CLI, run the following in your project’s root folder: + +```bash +amplify add auth ## "amplify update auth" if already configured +``` + +Choose the following options (the last steps are specific to Facebook in this example but these steps are similar for other providers): + +```console +? Do you want to use the default authentication and security configuration? + `Default configuration with Social Provider (Federation)` +? How do you want users to be able to sign in? + `Username` +? Do you want to configure advanced settings? + `No, I am done.` +? What domain name prefix you want us to create for you? + `(default)` +? Enter your redirect signin URI: + `http://localhost:3000/` +? Do you want to add another redirect signin URI + `No` +? Enter your redirect signout URI: + `http://localhost:3000/` +? Do you want to add another redirect signout URI + `No` +? Select the social providers you want to configure for your user pool: + `` +``` + + + +**Note:** You can configure your application to use more than one redirect URL. For more information, refer to the [Redirect URLs](#redirect-urls) section below. + + + +Next, run `amplify push` to publish your changes. Once finished, it will display an auto generated URL for your web UI. You can retrieve your user pool domain URL at anytime by running `amplify status` using the CLI. + +You need to now inform your auth provider of this URL: + + + + +1. [Sign In](https://developers.facebook.com/) to your Facebook developer account with your Facebook credentials. + +2. Choose *My Apps* from the top navigation bar, and on the *Apps* page, choose your app you created before. + +3. On the left navigation bar, choose *Products*. Add *Facebook Login* if it isn't already added. + +4. If already added, choose *Settings* under the *Configure* dropdown. +![The Settings option is circled from the configure dropdown.](/images/cognitoHostedUI/facebook5.png) + +5. Under *Valid OAuth Redirect URIs* type your user pool domain with the `/oauth2/idpresponse` endpoint. + + `https:///oauth2/idpresponse` + +![Userpool domain is pasted into the text field with /oauth2/ endpoint.](/images/cognitoHostedUI/facebook6.png) + +6. Save your changes. + + + + +1. Go to the [Google developer console](https://console.developers.google.com). + +2. On the left navigation bar, look for *APIs and Services* under *Pinned* or under *More Products* if not pinned. + +3. Within the *APIs and Services* sub menu, choose *Credentials*. + +4. Select the client you created in the first step and click the *Edit* button. + +5. Type your user pool domain into the *Authorized Javascript origins* form. + +6. Type your user pool domain with the `/oauth2/idpresponse` endpoint into *Authorized Redirect URIs*. + + ![The URLs 1 form fields for authorized Javascript origins and authorized redirect URLs are circled.](/images/cognitoHostedUI/google8.png) + + Note: If you saw an error message `Invalid Redirect: domain must be added to the authorized domains list before submitting.` when adding the endpoint, please go to the *Authorized Domains List* and add the domain. + +7. Click *Save*. + + + + +1. [Sign in](https://developer.amazon.com/loginwithamazon/console/site/lwa/overview.html) with your Amazon credentials. + +2. Hover over the gear and choose *Web Settings* associated with the security profile you created in the previous step, and then choose *Edit*. +![The web settings option is selected in the dropdown menu from the gear icon.](/images/cognitoHostedUI/amazon4.png) + +3. Type your user pool domain into *Allowed Origins* and type your user pool domain with the `/oauth2/idpresponse` endpoint into *Allowed Return URLs*. +![Userpool domain is typed into the allowed origins field with /oauth2/ as the endpoint in the Allowed Return URLs field.](/images/cognitoHostedUI/amazon5.png) + +4. Choose *Save*. + + + + +1. [Sign In](https://developer.apple.com/account/) with your Apple developer credentials. + +2. On the main developer portal page, select *Certificates, IDs, & Profiles*. + +3. On the left navigation bar, select *Identifiers* and then select *Service IDs* from the drop down list on the right. + +4. Select the service ID created when you set up your auth provider as outlined in the section above. + +5. Enable *Sign In with Apple* and select *Configure*. + +6. Under *Primary App ID* select the app ID that was created before. + +7. Type your user pool domain into *Domains and Subdomains*. + +8. Type your user pool domain with the `/oauth2/idpresponse` endpoint into *Return URLs*. +![The return URLs text field is selected.](/images/cognitoHostedUI/apple3.png) + +9. Click *Next*, review the information, then select *Done*. + +10. On *Edit your Services ID Configuration* click *Continue*, review the information, then select *Save*. + +11. On the main *Certificates, Identifiers & Profiles*, select *Keys*. + +12. On the *Keys* page, select the *+* icon. + +13. Provide a name for the key under *Key Name*. + +14. Enable *Sign in with Apple* and select *Configure*. +![The sign in with apple option is enabled and the key name text field is filled out.](/images/cognitoHostedUI/apple4.png) + +15. Under *Primary App ID* select the app ID that was created before. + +16. Click on *Save*. + +17. On *Register a New Key* click *Continue*, review the information, then select *Register*. + +18. You will be redirected to a new page. Take note of the *Key ID* and download the .p8 file containing the private key. +![The download key page is shown with the option to download the .p8 file with the private key.](/images/cognitoHostedUI/apple5.png) + + + + + + +Federated sign-in does not invoke any [Custom authentication challenge Lambda triggers](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html), [Migrate user Lambda trigger](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html), [Custom message Lambda trigger](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html), or [Custom sender Lambda triggers](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sender-triggers.html) in your user pool. For information on the supported Lambda triggers refer to the [AWS documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#lambda-triggers-for-federated-users) + + + +You have configured your Auth category and can now set up the frontend for your application. + + + + + +TODO + +## Setup frontend + +After configuring the OAuth endpoints (Cognito Hosted UI), you can integrate your App by invoking `Auth.federatedSignIn()` function. Passing `LoginWithAmazon`, `Facebook`, `Google`, or `SignInWithApple` on the `provider` argument (e.g `Auth.federatedSignIn({ provider: 'LoginWithAmazon' })`) will bypass the Hosted UI and federate immediately with the social provider as shown in the below React example. If you are looking to add a custom state, you are able to do so by passing a string (e.g. `Auth.federatedSignIn({ customState: 'xyz' })`) value and listening for the custom state via Hub. + + + + +```ts +import React, { useEffect, useState } from 'react'; +import { Amplify, Auth, Hub } from 'aws-amplify'; +import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth'; +import awsConfig from './aws-exports'; + +Amplify.configure(awsConfig); + +function App() { + const [user, setUser] = useState(null); + const [customState, setCustomState] = useState(null); + + useEffect(() => { + const unsubscribe = Hub.listen("auth", ({ payload: { event, data }}) => { + switch (event) { + case "signIn": + setUser(data); + break; + case "signOut": + setUser(null); + break; + case "customOAuthState": + setCustomState(data); + } + }); + + getUser(); + + return unsubscribe; + }, []); + + const getUser = async (): Promise => { + try { + const currentUser = await Auth.currentAuthenticatedUser(); + setUser(currentUser); + } catch(error) { + console.error(error); + console.log("Not signed in"); + } + }; + + return ( +
+ + + + + + +
{user?.getUsername()}
+
+ ); +} +``` +
+ + +```javascript +import React, { useEffect, useState } from 'react'; +import { Amplify, Auth, Hub } from 'aws-amplify'; +import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth'; +import awsConfig from './aws-exports'; + +Amplify.configure(awsConfig); + +function App() { + const [user, setUser] = useState(null); + const [customState, setCustomState] = useState(null); + + useEffect(() => { + const unsubscribe = Hub.listen("auth", ({ payload: { event, data } }) => { + switch (event) { + case "signIn": + setUser(data); + break; + case "signOut": + setUser(null); + break; + case "customOAuthState": + setCustomState(data); + } + }); + + Auth.currentAuthenticatedUser() + .then(currentUser => setUser(currentUser)) + .catch(() => console.log("Not signed in")); + + return unsubscribe; + }, []); + + return ( +
+ + + + + + +
{user && user.getUsername()}
+
+ ); +} +``` +
+
+ + + +You can also use the [Authenticator UI component](https://ui.docs.amplify.aws/react/components/authenticator) to add social sign in flow to your application. Visit [Social Provider](https://ui.docs.amplify.aws/react/components/authenticator/configuration#social-providers) section to learn more. + + + +### Deploying to Amplify Console + +To deploy your app to Amplify Console with continuous deployment of the frontend and backend, please follow [these instructions](https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html#creating-a-new-backend-environment-with-authentication-parameters). + +### Redirect URLs + +For *Sign in Redirect URI(s)* inputs, you can put one URI for local development and one for production. Example: `http://localhost:3000/` in dev and `https://www.example.com/` in production. The same is true for *Sign out redirect URI(s)*. + +**Note:** if you have multiple redirect URI inputs, you'll need to handle both of them where you configure your Amplify project. For example: + +```javascript +import awsConfig from './aws-exports'; + +const isLocalhost = Boolean( + window.location.hostname === "localhost" || + // [::1] is the IPv6 localhost address. + window.location.hostname === "[::1]" || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +// Assuming you have two redirect URIs, and the first is for localhost and second is for production +const [ + localRedirectSignIn, + productionRedirectSignIn, +] = awsConfig.oauth.redirectSignIn.split(","); + +const [ + localRedirectSignOut, + productionRedirectSignOut, +] = awsConfig.oauth.redirectSignOut.split(","); + +const updatedAwsConfig = { + ...awsConfig, + oauth: { + ...awsConfig.oauth, + redirectSignIn: isLocalhost ? localRedirectSignIn : productionRedirectSignIn, + redirectSignOut: isLocalhost ? localRedirectSignOut : productionRedirectSignOut, + } +} + +Amplify.configure(updatedAwsConfig); +``` + +### Full Sample + + + + +```ts +import { useEffect, useState } from 'react'; +import { Amplify, Auth, Hub } from 'aws-amplify'; +import awsConfig from './aws-exports'; + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +// Assuming you have two redirect URIs, and the first is for localhost and second is for production +const [ + localRedirectSignIn, + productionRedirectSignIn, +] = awsConfig.oauth.redirectSignIn.split(','); + +const [ + localRedirectSignOut, + productionRedirectSignOut, +] = awsConfig.oauth.redirectSignOut.split(','); + +const updatedAwsConfig = { + ...awsConfig, + oauth: { + ...awsConfig.oauth, + redirectSignIn: isLocalhost ? localRedirectSignIn : productionRedirectSignIn, + redirectSignOut: isLocalhost ? localRedirectSignOut : productionRedirectSignOut, + } +} + +Amplify.configure(updatedAwsConfig); + +function App() { + const [user, setUser] = useState(null); + + useEffect(() => { + Hub.listen('auth', ({ payload: { event, data }}) => { + switch (event) { + case 'signIn': + case 'cognitoHostedUI': + getUser(); + break; + case 'signOut': + setUser(null); + break; + case 'signIn_failure': + case 'cognitoHostedUI_failure': + console.log('Sign in failure', data); + break; + } + }); + + getUser(); + }, []); + + const getUser = async (): Promise => { + try { + const userData = await Auth.currentAuthenticatedUser(); + setUser(userData) + } catch(error) { + console.error(error); + console.log("Not signed in"); + } + }; + + return ( +
+

User: {user ? JSON.stringify(user.attributes) : 'None'}

+ {user ? ( + + ) : ( + + )} +
+ ); +} + +export default App; +``` +
+ + +```js +import { useEffect, useState } from 'react'; +import { Amplify, Auth, Hub } from 'aws-amplify'; +import awsConfig from './aws-exports'; + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +// Assuming you have two redirect URIs, and the first is for localhost and second is for production +const [ + localRedirectSignIn, + productionRedirectSignIn, +] = awsConfig.oauth.redirectSignIn.split(','); + +const [ + localRedirectSignOut, + productionRedirectSignOut, +] = awsConfig.oauth.redirectSignOut.split(','); + +const updatedAwsConfig = { + ...awsConfig, + oauth: { + ...awsConfig.oauth, + redirectSignIn: isLocalhost ? localRedirectSignIn : productionRedirectSignIn, + redirectSignOut: isLocalhost ? localRedirectSignOut : productionRedirectSignOut, + } +} + +Amplify.configure(updatedAwsConfig); + +function App() { + const [user, setUser] = useState(null); + + useEffect(() => { + Hub.listen('auth', ({ payload: { event, data } }) => { + switch (event) { + case 'signIn': + case 'cognitoHostedUI': + getUser().then(userData => setUser(userData)); + break; + case 'signOut': + setUser(null); + break; + case 'signIn_failure': + case 'cognitoHostedUI_failure': + console.log('Sign in failure', data); + break; + } + }); + + getUser().then(userData => setUser(userData)); + }, []); + + function getUser() { + return Auth.currentAuthenticatedUser() + .then(userData => userData) + .catch(() => console.log('Not signed in')); + } + + return ( +
+

User: {user ? JSON.stringify(user.attributes) : 'None'}

+ {user ? ( + + ) : ( + + )} +
+ ); +} + +export default App; +``` +
+
+ +### Catching Errors + +In order to catch errors when using `Auth.federatedSignIn()` you can use the [Hub](/lib/utilities/hub/q/platform/js/) eventing system provided by Amplify to listen for the `signIn_failure` event. + + + + +```ts +import { Hub } from 'aws-amplify' + +Hub.listen('auth', (data) => { + if (data.payload.event === 'signIn_failure') { + // Do something here + } +}) +``` + + + + +```js +import { Hub } from 'aws-amplify' + +Hub.listen('auth', (data) => { + if (data.payload.event === 'signIn_failure') { + // Do something here + } +}) +``` + + + +## Conclusion + +Congratulations! You finished the **Add social provider sign-in** guide. In this guide, you learned how to set up your auth provider, configure the Amplify Auth category, and set up the frontend. Your users can now sign in to your app using their social provider accounts. + +## Next steps + +Now that you updated how your credentials are managed you may also want to further refine the sing-in and sign-out workflows as well as update how you listen for these Auth events. We recommend you learn more about: + +- [Enable sign-up, sign-in, and sign-out](/lib/auth/emailpassword/q/platform/js/) +- [Auth events](/lib/auth/auth-events/q/platform/js/) + +
import reactnative0 from "/src/fragments/lib/auth/js/react-native-social.mdx"; From c2601f0015df406e3546d68495402004acf3be07 Mon Sep 17 00:00:00 2001 From: heatheramz <119376175+heatheramz@users.noreply.github.com> Date: Mon, 18 Sep 2023 10:58:16 -0700 Subject: [PATCH 010/164] Second half update for js content --- .../lib/auth/social/q/platform/[platform].mdx | 105 ++++++++---------- 1 file changed, 46 insertions(+), 59 deletions(-) diff --git a/src/pages/lib/auth/social/q/platform/[platform].mdx b/src/pages/lib/auth/social/q/platform/[platform].mdx index 51340c2314e..2ef85392c61 100644 --- a/src/pages/lib/auth/social/q/platform/[platform].mdx +++ b/src/pages/lib/auth/social/q/platform/[platform].mdx @@ -5,29 +5,33 @@ export const meta = { -[comment]: # (source content from src/fragments/lib/auth/js/social.mdx ; src/fragments/lib/auth/common/setup_auth_provider.mdx ; src/fragments/lib/auth/common/configure_auth_category.mdx ; /src/fragments/cli/lambda_triggers_callout.mdx) +[comment]: # (source content from src/fragments/lib/auth/js/social.mdx ; src/fragments/lib/auth/common/setup_auth_provider.mdx ; src/fragments/lib/auth/common/configure_auth_category.mdx ; /src/fragments/cli/lambda_triggers_callout.mdx ; /src/fragments/lib/auth/js/overview.mdx) -You can enable your users to sign-in and authenticate with your application using their existing accounts with social providers like Apple, Amazon, Facebook, and Google. Once you configure your backend resources, you can use Authenticator or the Amplify Libraries to sign in users for that provider. This process will securely exchange credentials and gather user information. This information can then be used to create a new user in your app or link the social account to an existing user. Incorporating social provider sign-in provides your users with a streamlined registration, more sign-in options, and an integrated experience across their existing accounts and your application. +You can enable your users to sign-in and authenticate with your app using their existing accounts with social providers like Apple, Amazon, Facebook, and Google. Once you configure your backend resources, you can use Authenticator or the Amplify Libraries to sign in users for that provider. This process will securely exchange credentials and gather user information. This information can then be used to create a new user in your app or link the social account to an existing user. Incorporating social provider sign-in provides your users with a streamlined registration, more sign-in options, and an integrated experience across their existing accounts and your app. -In this guide we will review how you can add sign-in with social providers after you set up and configure your developer account with the provider. After this is set up you can use Authenticator or the Amplify Libraries to configure your Auth category and integrate with your app. +In this guide we will review how you can add sign-in with social providers by first setting up your developer account with the provider. After this is set up you can then use Authenticator or the Amplify CLI and Libraries to configure your Auth category and integrate social sign-in with your app. This guide will focus on the use of the Amplify CLI and Libraries for this integration. Before you begin you will need: - An Amplify project - The Amplify libraries installed and configured -## Set up your social auth provider - -Before you configure social sign-in with Amplify Auth you will need to set up your developer account with each provider you are using. + - +Incorporating social provider sign-in provides your users more sign-in options with providers such as Facebook, Google, or Amazon. The preferred way to do this is via an OAuth redirect which lets users sign in using their social media account and a corresponding user is created in User Pools. [OAuth 2.0](https://en.wikipedia.org/wiki/OAuth) is the common Authorization framework used by web and mobile applications for accessing user information ("scopes") in a limited manner. Common analogies you will hear in OAuth is that of boarding a plane or staying in a hotel - showing your identification is the authentication piece (signing into an app) and using the boarding pass/hotel key is what you are authorized to access. -OAuth support in Amplify uses Cognito User Pools and supports federation with social providers, which will automatically create a corresponding user in the User Pool after a login. [OIDC](https://en.wikipedia.org/wiki/OpenID_Connect) tokens are available in the app after the application has completed this process. +OAuth support in Amplify uses Cognito User Pools and supports federation with social providers, which will automatically create a corresponding user in the User Pool after a login. [OIDC](https://en.wikipedia.org/wiki/OpenID_Connect) tokens are available in the app after the application has completed this process. With this design you do not need to include an SDK for the social provider in your app. After you set up your developer account with these social providers you can configure the `Auth` category by running `amplify add auth` and selecting the social provider option and then use `Auth.federatedSignIn()` in your app to either show a pre-built "Hosted UI" or pass in a provider name (e.g. `Auth.federatedSignIn({provider: 'Facebook'})`) to interface directly and build your own UI. + +![Image](/images/SocialAuthZ.png) + +You can also get credentials directly from Identity Pools by passing tokens from a social provider directly to `Auth.federatedSignIn()`. However you will have to use that provider's SDK directly in your app and manage token refresh and auth flows manually. -
+## Set up your social auth provider + +Before you configure social sign-in with Amplify Auth you will need to set up your developer account with each provider you are using. @@ -190,7 +194,7 @@ Choose the following options (the last steps are specific to Facebook in this ex Next, run `amplify push` to publish your changes. Once finished, it will display an auto generated URL for your web UI. You can retrieve your user pool domain URL at anytime by running `amplify status` using the CLI. -You need to now inform your auth provider of this URL: +You need to now inform your social provider of this URL: @@ -297,17 +301,19 @@ Federated sign-in does not invoke any [Custom authentication challenge Lambda tr -You have configured your Auth category and can now set up the frontend for your application. - +You have configured your Auth category and updated your URL with the social providers. You can now set up the frontend for your app. +## Set up your frontend +After configuring the OAuth endpoints (Cognito Hosted UI), you can integrate your app by invoking the `Auth.federatedSignIn()` function. Passing `LoginWithAmazon`, `Facebook`, `Google`, or `SignInWithApple` on the `provider` argument (e.g `Auth.federatedSignIn({ provider: 'LoginWithAmazon' })`) will bypass the Hosted UI and federate immediately with the social provider as shown in the below React example. + -TODO +You can also use the [Authenticator UI component](https://ui.docs.amplify.aws/react/components/authenticator) to add social sign in flow to your application. Visit [Social Provider](https://ui.docs.amplify.aws/react/components/authenticator/configuration#social-providers) section to learn more. -## Setup frontend + -After configuring the OAuth endpoints (Cognito Hosted UI), you can integrate your App by invoking `Auth.federatedSignIn()` function. Passing `LoginWithAmazon`, `Facebook`, `Google`, or `SignInWithApple` on the `provider` argument (e.g `Auth.federatedSignIn({ provider: 'LoginWithAmazon' })`) will bypass the Hosted UI and federate immediately with the social provider as shown in the below React example. If you are looking to add a custom state, you are able to do so by passing a string (e.g. `Auth.federatedSignIn({ customState: 'xyz' })`) value and listening for the custom state via Hub. +If you are looking to add a custom state, you are able to do so by passing a string (e.g. `Auth.federatedSignIn({ customState: 'xyz' })`) value and listening for the custom state via [Hub](/lib/utilities/hub/q/platform/js/). You can also use Hub eventing system to catch errors when using `Auth.federatedSignIn()` by listening for the `signIn_failure` event. @@ -365,6 +371,13 @@ function App() { ); } + + //You can catch errors by listening to the signIn-failure event + Hub.listen('auth', (data) => { + if (data.payload.event === 'signIn_failure') { + // Do something here + } +}) ``` @@ -414,21 +427,24 @@ function App() { ); } + + //You can catch errors by listening to the signIn-failure event + Hub.listen('auth', (data) => { + if (data.payload.event === 'signIn_failure') { + // Do something here + } +}) ``` - - -You can also use the [Authenticator UI component](https://ui.docs.amplify.aws/react/components/authenticator) to add social sign in flow to your application. Visit [Social Provider](https://ui.docs.amplify.aws/react/components/authenticator/configuration#social-providers) section to learn more. +### Deploy backend environment with auth parameters for social sign-in - - -### Deploying to Amplify Console +When you update your authentication configuration, Amplify creates a new backend environment for your app. You then need to deploy your app to this new backend environment in order for your app to use the updated configuration. If you do not deploy your updated app to the new backend environment, it will continue using the previous authentication configuration and social sign-in will not work. -To deploy your app to Amplify Console with continuous deployment of the frontend and backend, please follow [these instructions](https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html#creating-a-new-backend-environment-with-authentication-parameters). +You can deploy your app to the Amplify Console with continuous deployment of the frontend and backend, please follow [these instructions](https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html#creating-a-new-backend-environment-with-authentication-parameters). -### Redirect URLs + For *Sign in Redirect URI(s)* inputs, you can put one URI for local development and one for production. Example: `http://localhost:3000/` in dev and `https://www.example.com/` in production. The same is true for *Sign out redirect URI(s)*. @@ -470,7 +486,7 @@ const updatedAwsConfig = { Amplify.configure(updatedAwsConfig); ``` -### Full Sample +#### Full Example using multiple redirect URIs @@ -645,48 +661,19 @@ export default App; -### Catching Errors - -In order to catch errors when using `Auth.federatedSignIn()` you can use the [Hub](/lib/utilities/hub/q/platform/js/) eventing system provided by Amplify to listen for the `signIn_failure` event. - - - - -```ts -import { Hub } from 'aws-amplify' - -Hub.listen('auth', (data) => { - if (data.payload.event === 'signIn_failure') { - // Do something here - } -}) -``` - - - - -```js -import { Hub } from 'aws-amplify' - -Hub.listen('auth', (data) => { - if (data.payload.event === 'signIn_failure') { - // Do something here - } -}) -``` - - + ## Conclusion -Congratulations! You finished the **Add social provider sign-in** guide. In this guide, you learned how to set up your auth provider, configure the Amplify Auth category, and set up the frontend. Your users can now sign in to your app using their social provider accounts. +Congratulations! You finished the **Add social provider sign-in** guide. In this guide, you learned how to set up your social auth provider, configure the Amplify Auth category for social sign-in, and set up the frontend. Your users can now sign into your app using their social provider accounts. ## Next steps -Now that you updated how your credentials are managed you may also want to further refine the sing-in and sign-out workflows as well as update how you listen for these Auth events. We recommend you learn more about: +Now that you social provider sign-in you may also want to learn more additional ways to customize these workflows. We recommend you learn more about: -- [Enable sign-up, sign-in, and sign-out](/lib/auth/emailpassword/q/platform/js/) -- [Auth events](/lib/auth/auth-events/q/platform/js/) +- [Password and user management](/lib/auth/manageusers/q/platform/js/) +- [Identity Pool Federation](/lib/auth/advanced/q/platform/js/#identity-pool-federation) +- [Working with Hub](lib/utilities/hub/q/platform/js/)
From 1e7b520d313b4085bbf7b8449025718dac0bf195 Mon Sep 17 00:00:00 2001 From: heatheramz <119376175+heatheramz@users.noreply.github.com> Date: Mon, 18 Sep 2023 14:06:45 -0700 Subject: [PATCH 011/164] Added React Native content --- .../lib/auth/social/q/platform/[platform].mdx | 895 +++++++++++++++++- 1 file changed, 881 insertions(+), 14 deletions(-) diff --git a/src/pages/lib/auth/social/q/platform/[platform].mdx b/src/pages/lib/auth/social/q/platform/[platform].mdx index 2ef85392c61..b4b407d27d1 100644 --- a/src/pages/lib/auth/social/q/platform/[platform].mdx +++ b/src/pages/lib/auth/social/q/platform/[platform].mdx @@ -3,13 +3,13 @@ export const meta = { description: `Learn how to setup social sign-in providers like Facebook, Google, Amazon, or Sign in with Apple.`, }; - + -[comment]: # (source content from src/fragments/lib/auth/js/social.mdx ; src/fragments/lib/auth/common/setup_auth_provider.mdx ; src/fragments/lib/auth/common/configure_auth_category.mdx ; /src/fragments/cli/lambda_triggers_callout.mdx ; /src/fragments/lib/auth/js/overview.mdx) +[comment]: # (source content from src/fragments/lib/auth/js/social.mdx ; src/fragments/lib/auth/common/setup_auth_provider.mdx ; src/fragments/lib/auth/common/configure_auth_category.mdx ; /src/fragments/cli/lambda_triggers_callout.mdx ; /src/fragments/lib/auth/js/overview.mdx ; /src/fragments/lib/auth/js/react-native-social.mdx ; /src/fragments/lib/auth/js/react-native-withoauth.mdx) -You can enable your users to sign-in and authenticate with your app using their existing accounts with social providers like Apple, Amazon, Facebook, and Google. Once you configure your backend resources, you can use Authenticator or the Amplify Libraries to sign in users for that provider. This process will securely exchange credentials and gather user information. This information can then be used to create a new user in your app or link the social account to an existing user. Incorporating social provider sign-in provides your users with a streamlined registration, more sign-in options, and an integrated experience across their existing accounts and your app. +You can enable your users to sign-in and authenticate with your app using their existing accounts with social providers like Apple, Amazon, Facebook, and Google. Once you configure your backend resources, you can configure your app to sign in users for that provider. This process will securely exchange credentials and gather user information. This information can then be used to create a new user in your app or link the social account to an existing user. Incorporating social provider sign-in provides your users with a streamlined registration, more sign-in options, and an integrated experience across their existing accounts and your app. -In this guide we will review how you can add sign-in with social providers by first setting up your developer account with the provider. After this is set up you can then use Authenticator or the Amplify CLI and Libraries to configure your Auth category and integrate social sign-in with your app. This guide will focus on the use of the Amplify CLI and Libraries for this integration. +In this guide we will review how you can add sign-in with social providers by first setting up your developer account with the provider. After this is set up you can then configure your Auth category and integrate social sign-in with your app. Before you begin you will need: - An Amplify project @@ -149,7 +149,17 @@ Your developer accounts with the social providers are now set up and you can ret ## Configure the Auth category -Once you have the social providers configured you can update your Auth configuration through the Amplify CLI or use the out-of-box set up through [Authenticator](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#social-providers). The steps below outline using the CLI. +Once you have the social providers configured you can update your Auth configuration through the Amplify CLI. + + + + + +**Note:** You can also use the out-of-box set up through [Authenticator](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#social-providers). + + + + @@ -305,7 +315,9 @@ You have configured your Auth category and updated your URL with the social prov ## Set up your frontend -After configuring the OAuth endpoints (Cognito Hosted UI), you can integrate your app by invoking the `Auth.federatedSignIn()` function. Passing `LoginWithAmazon`, `Facebook`, `Google`, or `SignInWithApple` on the `provider` argument (e.g `Auth.federatedSignIn({ provider: 'LoginWithAmazon' })`) will bypass the Hosted UI and federate immediately with the social provider as shown in the below React example. +After configuring the OAuth endpoints (Cognito Hosted UI), you can integrate your app by invoking the `Auth.federatedSignIn()` function. Passing `LoginWithAmazon`, `Facebook`, `Google`, or `SignInWithApple` on the `provider` argument (e.g `Auth.federatedSignIn({ provider: 'LoginWithAmazon' })`) will bypass the Hosted UI and federate immediately with the social provider as shown in the below example. + + @@ -438,17 +450,140 @@ function App() { -### Deploy backend environment with auth parameters for social sign-in + -When you update your authentication configuration, Amplify creates a new backend environment for your app. You then need to deploy your app to this new backend environment in order for your app to use the updated configuration. If you do not deploy your updated app to the new backend environment, it will continue using the previous authentication configuration and social sign-in will not work. + -You can deploy your app to the Amplify Console with continuous deployment of the frontend and backend, please follow [these instructions](https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html#creating-a-new-backend-environment-with-authentication-parameters). +If you are looking to add a custom state, you are able to do so by passing a string (e.g. `Auth.federatedSignIn({ customState: 'xyz' })`) value and listening for the custom state via [Hub](/lib/utilities/hub/q/platform/react-native/). + + + + +```ts +import { useEffect, useState } from "react"; +import { Text, View, Linking, Button } from "react-native"; +import { CognitoHostedUIIdentityProvider } from "@aws-amplify/auth"; +import { Amplify, Auth, Hub } from "aws-amplify"; +import awsconfig from "./aws-exports"; + +Amplify.configure(awsconfig); + +export default function App() { + const [user, setUser] = useState(null); + const [customState, setCustomState] = useState(null); + + useEffect(() => { + const unsubscribe = Hub.listen("auth", ({ payload: { event, data }}) => { + switch (event) { + case "signIn": + setUser(data); + break; + case "signOut": + setUser(null); + break; + case "customOAuthState": + setCustomState(data); + } + }); - + getUser(); + + return unsubscribe; + }, []); + + const getUser = async (): Promise => { + try { + const currentUser = await Auth.currentAuthenticatedUser(); + setUser(currentUser); + } catch(error) { + console.error(error); + console.log("Not signed in"); + } + }; + + return ( + + + + ); +} + +export default function App() { + const [showValidationCodeUI, setShowValidationCodeUI] = useState(false); + + return ( + + {({ signOut, user }) => ( +
+
+
{JSON.stringify(user?.attributes, null, 2)}
+
+ {showValidationCodeUI === false && ( + + )} + {showValidationCodeUI === true && } + +
+ )} +
+ ); +} +``` +
+ + +```javascript +// App.js +import { Authenticator } from '@aws-amplify/ui-react'; +import '@aws-amplify/ui-react/styles.css'; +import { Auth } from 'aws-amplify'; +import { useState } from 'react'; + +async function updateUserEmail() { + try { + const user = await Auth.currentAuthenticatedUser(); + await Auth.updateUserAttributes(user, { + email: 'updatedEmail@mydomain.com' + }); + + console.log('a verification code is sent'); + } catch(err) { + console.log('failed with error', err); + } +} + +async function verifyEmailValidationCode(code) { + try { + await Auth.verifyCurrentUserAttributeSubmit('email', code); + console.log('email verified'); + } catch(err) { + console.log('failed with error', err); + } +} + +function ValidationCodeForm() { + const [validationCode, setValidationCode] = useState(null); + return ( +
+ + +
+ ); +} + +export default function App() { + const [showValidationCodeUI, setShowValidationCodeUI] = useState(false); + + return ( + + {({ signOut, user }) => ( +
+
+
{JSON.stringify(user.attributes, null, 2)}
+
+ {showValidationCodeUI === false && ( + + )} + {showValidationCodeUI === true && } + +
+ )} +
+ ); +} +``` +
+
+ + + +### Delete user attributes + +Finally, if your users need to delete one or more user attributes, you can call `Auth.deleteUserAttributes` method of the `Auth` class to enable this action: + +```ts +import { Auth } from 'aws-amplify'; + +async function deleteUserAttributes() { + try { + const user = await Auth.currentAuthenticatedUser(); + const result = await Auth.deleteUserAttributes(user, ['family_name']); + console.log(result); // SUCCESS + } catch(err) { + console.log(err); + } +}; +``` + +## Conclusion + +Congratulations! You finished the **Manage user profiles** guide and your users can now review and customize their profile information. + +## Next steps + +Now that you completed setting up user profile management, you may also want to add some additional features. We recommend: + - [Set up password change and recovery](/lib/auth/password_management/q/platform/js/) + - [Custom Attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-custom-attributes) + +
From e00514fa15260c460dcde6eafb8152508e265f44 Mon Sep 17 00:00:00 2001 From: heatheramz <119376175+heatheramz@users.noreply.github.com> Date: Thu, 21 Sep 2023 13:31:23 -0700 Subject: [PATCH 016/164] Updating directory for password mgmt --- src/directory/directory.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs index 6570e4647e2..fd33f3d49e4 100644 --- a/src/directory/directory.mjs +++ b/src/directory/directory.mjs @@ -358,9 +358,9 @@ export const directory = { filters: ['android', 'ios', 'js', 'flutter', 'react-native'] }, { - title: 'Password management', + title: 'Set up password change and recovery', route: '/lib/auth/password_management', - filters: ['android', 'flutter', 'ios'] + filters: ['js', 'react-native', 'android', 'flutter', 'ios'] }, { title: 'Sign out', From b537ab834b888a6e825f6ba2374f22ef1b6564b5 Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Fri, 22 Sep 2023 17:51:19 -0700 Subject: [PATCH 017/164] Updates for password management --- .../q/platform/[platform].mdx | 217 +++++++++++++++++- 1 file changed, 215 insertions(+), 2 deletions(-) diff --git a/src/pages/lib/auth/password_management/q/platform/[platform].mdx b/src/pages/lib/auth/password_management/q/platform/[platform].mdx index 0006f255d37..08c7f661e96 100644 --- a/src/pages/lib/auth/password_management/q/platform/[platform].mdx +++ b/src/pages/lib/auth/password_management/q/platform/[platform].mdx @@ -1,8 +1,221 @@ export const meta = { - title: `Password management`, - description: `Use AWS Cognito Auth plugin to update or reset user password`, + title: `Set up password change and recovery`, + description: `Set up password change and recovery for your application.`, }; + + +[comment]: # (IMPORTANT - Password content moved from manageusers - should be pushed at same time. Also we noted to move "resend sign-up confirmation code" to this page from /src/fragments/lib/auth/js/emailpassword.mdx but reading it in context it may fit better after this section - lib/auth/emailpassword/q/platform/js/#confirm-sign-up. Source content below from /src/fragments/lib/auth/js/manageusers.mdx ; lib/auth/emailpassword/q/platform/js/) + +Amplify Auth provides a secure way for your users to change their password or recover a forgotten password. This securely reduces friction for your users and improves their experience accessing your application. + +Before you being, you will need: + +- An Amplify project with the Auth category configured +- The Amplify libraries installed and configured + +## Allow my customers to change their password + +You can expect that your users will need to change their password over time or create a new one when they forget their password. You can set this up using the Amplify Libraries. + +### Change to a new password during sign-up + +There may be instances when you need your users to update their password. For example, this may be needed as part of updating a temporary password. You can prompt your users to create a new password and enter any additional required attributes during their first sign-in attempt after a valid user directory is created in Amazon Cognito. Your user will be prompted to make this change with the challenge for a `NEW_PASSWORD_REQUIRED`. During this scenario, the `completeNewPassword` method can be called to process the new password entered by your user. This will set the new password for the user and update any required attributes. The user will then be signed in. + + + + +```ts +import { Auth } from 'aws-amplify'; + +async function completeNewPassword(username: string, password: string) { + try { + const user = await Auth.signIn(username, password); + + if (user.challengeName === 'NEW_PASSWORD_REQUIRED') { + const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number'] + } +const newPassword = 'newPassword' + const loggedInUser = await Auth.completeNewPassword( + user, // the Cognito User Object + newPassword, // the new password + // OPTIONAL, the required attributes + { + email: 'xxxx@example.com', + phone_number: '1234567890' + } + ) + + console.log(loggedInUser); + } catch(err) { + console.log(err); + } +}; +``` + + + +```js +import { Auth } from 'aws-amplify'; + +async function completeNewPassword(username, password) { + try { + const user = await Auth.signIn(username, password); +const newPassword = 'newPassword' + if (user.challengeName === 'NEW_PASSWORD_REQUIRED') { + const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number'] + const loggedInUser = await Auth.completeNewPassword( + user, // the Cognito User Object + newPassword, // the new password + // OPTIONAL, the required attributes + { + email: 'xxxx@example.com', + phone_number: '1234567890' + } + ) + + console.log(loggedInUser); + } + } catch(err) { + console.log(err); + } +}; +``` + + + +### Change a password + +You can enable customers to change passwords using the `changePassword` method. This will prompt the user to enter their current password `oldPassword` and a new password `newPassword`. If successful, the password will be updated. + + + + +```ts +import { Auth } from 'aws-amplify'; + +async function changePassword (oldPassword: string, newPassword: string) { + try { + const user = await Auth.currentAuthenticatedUser(); + const data = await Auth.changePassword(user, oldPassword, newPassword); + console.log(data); + } catch(err) { + console.log(err); + } +}; +``` + + + +```javascript +import { Auth } from 'aws-amplify'; + +async function changePassword (oldPassword, newPassword) { + try { + const user = await Auth.currentAuthenticatedUser(); + const data = await Auth.changePassword(user, oldPassword, newPassword); + console.log(data); + } catch(err) { + console.log(err); + } +}; +``` + + + + + +You may get form validation errors when your user enters an invalid password that does not meet the requirements you have set. For example, if you require a minimum length of eight characters, you'll need to handle displaying an error message if the user enters less than eight. + +You will also want to wrap your API calls with `try` and `catch` blocks to catch any errors. You can then display user-friendly error messages in the UI so your users know what happened. This will make sure you don't have any silent failures in your user experience. + + + +Your users now have access to change their passwords. + +## Allow my users to replace a forgotten password + +In other instances your users may want to retrieve a forgotten password. You can enable this by using the `forgotPassword` method. This will send a confirmation code to your user's email or phone number (depending on which attributes are verified in your Cognito user pool) and they can then enter that confirmation code with a new password using the `forgotPasswordSubmit` method. This will allow the user to reset their password and sign in with the new password. + + + + +```ts +// Send confirmation code to user's email +async function forgotPassword(username: string) { + try { + const data = await Auth.forgotPassword(username); + console.log(data); + } catch(err) { + console.log(err); + } +}; + +// Collect confirmation code and new password +async function forgotPasswordSubmit(username: string, code: string, newPassword: string) { + try { + const data = await Auth.forgotPasswordSubmit(username, code, newPassword); + console.log(data); + } catch(err) { + console.log(err); + } +}; +``` + + + +```javascript +import { Auth } from 'aws-amplify'; + +// Send confirmation code to user's email +async function forgotPassword(username) { + try { + const data = await Auth.forgotPassword(username); + console.log(data); + } catch(err) { + console.log(err); + } +} + +// Collect confirmation code and new password +async function forgotPasswordSubmit(username, code, newPassword) { + try { + const data = await Auth.forgotPasswordSubmit(username, code, newPassword); + console.log(data); + } catch(err) { + console.log(err); + } +} +``` + + + +Your users can now recover their account and reset to a new password. + +## Conclusion + +Congratulations! You finished the **Set up password change and recovery** guide. In this guide, you learned how to enable password changes by your users and help them recover their account and replace their password using a registered email or phone number. + +## Next steps + +Now that you enabled password management you may also want to add some additional features. We recommend you learn more about: + + + +- [Social sign-in (OAuth)](/lib/auth/social/q/platform/js/) +- [Multi-factor authentication](/lib/auth/mfa/q/platform/js/) + + + + + +- [Social sign-in (OAuth)](/lib/auth/social/q/platform/react-native/) +- [Multi-factor authentication](/lib/auth/mfa/q/platform/react-native/) + + + + + import ios0 from "/src/fragments/lib/auth/native_common/password_management/common.mdx"; From 31f7f0645cce18becb50a5250c7c809931b7558b Mon Sep 17 00:00:00 2001 From: Heather Pundt <119376175+heatheramz@users.noreply.github.com> Date: Mon, 25 Sep 2023 11:20:15 -0700 Subject: [PATCH 018/164] Updated wording and small edits --- .../q/platform/[platform].mdx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/pages/lib/auth/password_management/q/platform/[platform].mdx b/src/pages/lib/auth/password_management/q/platform/[platform].mdx index 08c7f661e96..5daf139c386 100644 --- a/src/pages/lib/auth/password_management/q/platform/[platform].mdx +++ b/src/pages/lib/auth/password_management/q/platform/[platform].mdx @@ -9,18 +9,18 @@ export const meta = { Amplify Auth provides a secure way for your users to change their password or recover a forgotten password. This securely reduces friction for your users and improves their experience accessing your application. -Before you being, you will need: +Before you begin, you will need: - An Amplify project with the Auth category configured - The Amplify libraries installed and configured ## Allow my customers to change their password -You can expect that your users will need to change their password over time or create a new one when they forget their password. You can set this up using the Amplify Libraries. +You may want your users to be able to change their password over time. You can set this up using the Amplify Libraries. -### Change to a new password during sign-up +### Change to a new password during sign-in -There may be instances when you need your users to update their password. For example, this may be needed as part of updating a temporary password. You can prompt your users to create a new password and enter any additional required attributes during their first sign-in attempt after a valid user directory is created in Amazon Cognito. Your user will be prompted to make this change with the challenge for a `NEW_PASSWORD_REQUIRED`. During this scenario, the `completeNewPassword` method can be called to process the new password entered by your user. This will set the new password for the user and update any required attributes. The user will then be signed in. +There may be instances when you need your users to update their password during sign-in. For example, this may be needed as part of updating a temporary password used to sign-up. You can prompt your users to create a new password and enter any additional required attributes during their first sign-in attempt after a valid user directory is created in Amazon Cognito. Your user will be prompted to make this change with the challenge for a `NEW_PASSWORD_REQUIRED`. During this scenario, the `completeNewPassword` method can be called to process the new password entered by your user. This will set the new password for the user and update any required attributes. The user will then be signed in. @@ -86,7 +86,7 @@ const newPassword = 'newPassword' ### Change a password -You can enable customers to change passwords using the `changePassword` method. This will prompt the user to enter their current password `oldPassword` and a new password `newPassword`. If successful, the password will be updated. +You can also enable customers to change passwords using the `changePassword` method. This will prompt the user to enter their current password `oldPassword` and a new password `newPassword`. If successful, the password will be updated. @@ -125,17 +125,19 @@ async function changePassword (oldPassword, newPassword) { -You may get form validation errors when your user enters an invalid password that does not meet the requirements you have set. For example, if you require a minimum length of eight characters, you'll need to handle displaying an error message if the user enters less than eight. +You may get form validation errors when your user enters an invalid password that does not meet the requirements you have set. For example, if you require a minimum length of eight characters, you'll need to display an error message if the user enters less than eight. You will also want to wrap your API calls with `try` and `catch` blocks to catch any errors. You can then display user-friendly error messages in the UI so your users know what happened. This will make sure you don't have any silent failures in your user experience. -Your users now have access to change their passwords. +
+ +Your users now have the ability to change their passwords. ## Allow my users to replace a forgotten password -In other instances your users may want to retrieve a forgotten password. You can enable this by using the `forgotPassword` method. This will send a confirmation code to your user's email or phone number (depending on which attributes are verified in your Cognito user pool) and they can then enter that confirmation code with a new password using the `forgotPasswordSubmit` method. This will allow the user to reset their password and sign in with the new password. +In other instances your users may want to retrieve access to their account and replace a forgotten password. You can enable this by using the `forgotPassword` method. This will send a confirmation code to your user's email or phone number (depending on which attributes are verified in your Cognito user pool) and they can then enter that confirmation code with a new password using the `forgotPasswordSubmit` method. This will allow the user to reset their password and sign in with the new password. From 676ffe720d1919e44b3028c4d390b170375d2fc3 Mon Sep 17 00:00:00 2001 From: Jim Eagan Date: Mon, 25 Sep 2023 15:39:05 -0700 Subject: [PATCH 019/164] docs (js): Copyedited Set up Amplify Auth guide --- .../getting-started/q/platform/[platform].mdx | 113 +++++++++--------- 1 file changed, 57 insertions(+), 56 deletions(-) diff --git a/src/pages/lib/auth/getting-started/q/platform/[platform].mdx b/src/pages/lib/auth/getting-started/q/platform/[platform].mdx index 6fdacec54c5..df9cd477ce8 100644 --- a/src/pages/lib/auth/getting-started/q/platform/[platform].mdx +++ b/src/pages/lib/auth/getting-started/q/platform/[platform].mdx @@ -9,14 +9,14 @@ import guide from "/src/fragments/common/guide-header.mdx"; -In this guide, you will learn how to set up Amplify **Auth**. This includes setting up and connecting your backend resources, determining your integration path, and enabling sign-up, sign-in, and sign-out with the Authenticator UI component. We will also provide more context on how resources are managed and created with Amplify to help you make decisions, and understand any long-term impact of those decisions. +In this guide, you will learn how to set up Amplify **Auth**. This includes setting up and connecting your backend resources, determining your integration path, and enabling sign-up, sign-in, and sign-out with the Authenticator UI component. We will also provide more context on how resources are managed and created with Amplify to help you make decisions and understand any long-term impact of those decisions. Before you begin, you will need: - [Node.js](https://nodejs.org/) v14.x or later - [npm](https://www.npmjs.com/) v6.14.4 or later - [git](https://git-scm.com/) v2.14.1 or later - A frontend app -- If you want Amplify to set up and manage your backend resources you need to [install and configure](/lib/project-setup/prereq/q/platform/js/) the Amplify CLI. Make sure to also create a new Amplify project using `amplify init` in your terminal, or pull in an existing Amplify project to your frontend app by using `amplify pull`. +- If you want Amplify to set up and manage your backend resources, you need to [install and configure](/lib/project-setup/prereq/q/platform/js/) the Amplify CLI. Make sure to also create a new Amplify project using `amplify init` in your terminal, or pull in an existing Amplify project to your frontend app by using `amplify pull`. ## Set up and connect backend resources @@ -24,15 +24,15 @@ We will review the paths to integrate Amplify Auth before you set up and integra ### Decide how to create and manage your backend resources -You can create and manage your Authentication resources with Amplify by using the Amplify CLI, Amplify Studio, or manage them yourself with tools such as CDK and CloudFormation. The path we recommend is via the Amplify CLI, which allows you to create new authentication resources or import existing ones. However, you can also use the Amplify Studio console to configure or use existing resources and directly connect them to your application using the Amplify Libraries. These tools will help you with creating and managing your resources. +You can create and manage your Authentication resources with Amplify by using the Amplify CLI, Amplify Studio, or manage them yourself with tools such as CDK and CloudFormation. The path we recommend is through the Amplify CLI, which allows you to create new authentication resources or import existing ones. However, you can also use the Amplify Studio console to configure or use existing resources and directly connect them to your application using the Amplify Libraries. These tools will help you with creating and managing your resources. -With Amplify Auth, you can use a username and password as an authentication method, use a social provider such as "Sign In with Google" or "Sign in With Apple," or create a fully custom authentication flow. +With Amplify Auth, you can use a username and password as an authentication method, use a social provider such as "Sign in with Google" or "Sign in with Apple," or create a fully custom authentication flow. Amplify helps you secure your application while providing an easy sign-in experience for your users. This experience is influenced by your security strategy. This security strategy includes the authentication method, security credentials, and enabling additional verification when needed. - - *Authentication* is a process to validate **who you are** (abbreviated as *AuthN*). The system which does this validation is referred to as an Identity Provider or IdP. This can be your own self-hosted IdP or a cloud service. Oftentimes, this IdP is a social provider such as Facebook, Google, or Amazon. + - *Authentication* is a process to validate **who you are** (abbreviated as *AuthN*). The system that does this validation is referred to as an Identity Provider or IdP. This can be your own self-hosted IdP or a cloud service. Oftentimes, this IdP is a social provider such as Facebook, Google, or Amazon. - *Authorization* is the process of validating **what you can access** (abbreviated as *AuthZ*). This is sometimes done by looking at tokens with custom logic, predefined rules, or signed requests with policies. Common authentication methods and associated risks include: @@ -41,32 +41,32 @@ Common authentication methods and associated risks include: You can improve security credentials and verification for these authentication methods by: - Adding password policies that ensure stronger passwords are created by your users. -- Require additional contact information from users before they can reset passwords. -- Add multi-factor authentication which adds a layer of security at sign-in but may also add friction for your users. +- Requiring additional contact information from users before they can reset passwords. +- Adding multi-factor authentication (MFA) which adds a layer of security at sign-in but may also add friction for your users.
-Amplify uses [Amazon Cognito](https://aws.amazon.com/cognito/) as the main authentication provider. Amazon Cognito is a robust user directory service that handles user registration, authentication, account recovery, and other operations. If you have not worked with Amazon Cognito before we recommend taking a closer look at Amazon Cognito configuration options before you continue, since some of them are irreversible after your resources are created. +Amplify uses [Amazon Cognito](https://aws.amazon.com/cognito/) as the main authentication provider. Amazon Cognito is a robust user directory service that handles user registration, authentication, account recovery, and other operations. If you have not worked with Amazon Cognito before, we recommend taking a closer look at Amazon Cognito configuration options before you continue, since some of them are irreversible after your resources are created. -Amazon Cognito can be customized based on your security strategy for authentication. However, there are some initial configuration options that cannot be changed after the backend resources are configured: +Amazon Cognito can be customized based on your security strategy for authentication. However, some initial configuration options cannot be changed after the backend resources are configured: -- User attributes that are used to identify your individual users (e.g. username, email, etc.) cannot be renamed or deleted. -- Sign-in methods (including username, email, phone, etc.) cannot be added or changed after the initial configuration. This includes both defining which attributes are used to sign in and which attributes are required. Required attributes must have a value for all users once set. -- Verification methods (including username, email, etc.) are the same as required attributes and cannot be removed once configured. +- User attributes that are used to identify your individual users (such as username and email) cannot be renamed or deleted. +- Sign-in methods (including username, email, and phone) cannot be added or changed after the initial configuration. This includes both defining which attributes are used to sign in and which attributes are required. Required attributes must have a value for all users once set. +- Verification methods (including username and email) are the same as required attributes and cannot be removed once configured. - The `sub` attribute is a unique identifier within each user pool that cannot be modified and can be used to index and search users. -- If MFA is set to required for all users, you will need to include MFA setup when users sign up. +- If MFA is set to **required** for all users, you will need to include MFA setup when users sign up. -See the [Amazon Cognito documentation]( https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) for more details on these settings including [User pool attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html) and [Adding MFA to a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html). +See the [Amazon Cognito documentation]( https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) for more details on these settings, including [User pool attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html) and [Adding MFA to a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html). ### Set up and configure Amplify Auth -In this section you will learn how to set up your backend resources and install the Amplify Libraries to use with your application. +In this section, you will learn how to set up your backend resources and install the Amplify Libraries to use with your application. #### Set up your Auth backend resources @@ -77,7 +77,7 @@ You can set up your backend resources with the Amplify CLI, Amplify Studio, or u > Prerequisites: [Install and configure](/lib/project-setup/prereq/q/platform/js/) the Amplify CLI in addition to the Amplify Libraries. -To start provisioning auth resources in the backend, go to your project directory and **execute the command**: +To start provisioning auth resources in the backend, go to your project directory and **run the command**: ```bash amplify add auth @@ -88,15 +88,15 @@ amplify add auth ? How do you want users to be able to sign in? Username ? Do you want to configure advanced settings? No, I am done. ``` -> If you have previously enabled an Amplify category that uses Auth behind the scenes (e.g. API category), you can run the `amplify update auth` command to edit your configuration if needed. +> If you have previously enabled an Amplify category that uses Auth behind the scenes (such as API category), you can run the `amplify update auth` command to edit your configuration if needed. The CLI prompts will help you to customize your auth flow for your app. With the provided options, you can: - Customize sign-in/registration flow -- Customize email and SMS messages for Multi-Factor Authentication -- Customize attributes for your users, e.g. name, email -- Enable 3rd party social providers, e.g. Facebook, Twitter, Google and Amazon +- Customize email and SMS messages for multi-factor authentication +- Customize attributes for your users, such as name and email +- Enable third-party social providers, such as Facebook, Twitter, Google, and Amazon -If you wish to federate with social providers [you will need to configure them first](/lib/auth/social#social-providers-and-federation). +If you wish to federate with social providers, [you will need to configure them first](/lib/auth/social#social-providers-and-federation). After configuring your Authentication options, update your backend and deploy the service by running the `push` command: @@ -104,13 +104,13 @@ After configuring your Authentication options, update your backend and deploy th amplify push ``` -Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command: +Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to the Amplify console by running the following command: ```bash amplify console ``` -In your app's entry point (i.e. **App.js**, **index.js**, **_app.js**, or **main.js**), import and load the configuration file: +In your app's entry point (specifically, **App.js**, **index.js**, **_app.js**, or **main.js**), import and load the configuration file: ```javascript import { Amplify, Auth } from 'aws-amplify'; @@ -124,7 +124,7 @@ Amplify.configure(awsconfig); > Prerequisites: [Install and configure](/lib/project-setup/prereq/q/platform/js/) the Amplify CLI in addition to the Amplify Libraries. -To import existing Amazon Cognito resources into your Amplify project, **execute the command**: +To import existing Amazon Cognito resources into your Amplify project, **run the command**: ```bash amplify import auth @@ -136,12 +136,12 @@ amplify import auth Cognito User Pool only ``` -Once you've selected an option, you'll be able to search for and import an existing Cognito User Pool and Identity Pool (or User Pool only) within your AWS account. The `amplify import auth` command will also do the following: +Once you've selected an option, you will be able to search for and import an existing Cognito User Pool and Identity Pool (or User Pool only) within your AWS account. The `amplify import auth` command will also do the following: - Automatically populate your Amplify Library configuration files (aws-exports.js, amplifyconfiguration.json) with your chosen Amazon Cognito resource information -- Provide your designated existing Cognito resource as the authentication & authorization mechanism for all auth-dependent categories (API, Storage and more) +- Provide your designated existing Cognito resource as the authentication and authorization mechanism for all auth-dependent categories (API, Storage, and more) - Enable Lambda functions to access the chosen Cognito resource if you permit it -> If you have previously enabled an Amplify category that uses Auth behind the scenes (e.g. API category), you can run the `amplify update auth` command to edit your configuration if needed. +> If you have previously enabled an Amplify category that uses Auth behind the scenes (such as API category), you can run the `amplify update auth` command to edit your configuration if needed. After configuring your Authentication options, update your backend and deploy the service by running the `push` command: @@ -149,13 +149,13 @@ After configuring your Authentication options, update your backend and deploy th amplify push ``` -Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command: +Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to the Amplify console by running the following command: ```bash amplify console ``` -In your app's entry point (i.e. **App.js**, **index.js**, **_app.js**, or **main.js**), import and load the configuration file: +In your app's entry point (specifically, **App.js**, **index.js**, **_app.js**, or **main.js**), import and load the configuration file: ```javascript import { Amplify, Auth } from 'aws-amplify'; @@ -169,19 +169,19 @@ Amplify.configure(awsconfig); > Prerequisites: [Install and configure](/lib/project-setup/prereq/q/platform/js/) the Amplify CLI in addition to the Amplify Libraries. -Amplify Studio allows you create auth resources, set up authorization rules, implement Multi-factor authentication (MFA), and more via an intuitive UI. To set up Authentication through the Amplify Studio, take the following steps: +Amplify Studio allows you to create auth resources, set up authorization rules, implement multi-factor authentication (MFA), and more through an intuitive UI. To set up Authentication through Amplify Studio, take the following steps: 1. **Sign in** to the [AWS Management Console](https://console.aws.amazon.com/console/home) and open AWS Amplify. 2. In the navigation pane, **choose an application**. 3. On the application information page, choose the **Backend environments** tab, then choose **Launch Studio**. 4. On the **Set up** menu, choose **Authentication**. -5. In the **Configure log in** section, choose a login mechanism to add from the **Add login mechanism** list. Valid options are _Username_, _Phone number_, _Facebook_, _Google_, _Amazon_, and _Sign in with Apple_. If you choose one of the social sign-in mechanisms (i.e. _Facebook_, _Google_, _Amazon_, or _Sign in with Apple_), you will also need to enter your _App ID_, _App Secret_, and redirect URLs. +5. In the **Configure login** section, choose a login mechanism to add from the **Add login mechanism** list. Valid options are _Username_, _Phone number_, _Facebook_, _Google_, _Amazon_, and _Sign in with Apple_. If you choose one of the social sign-in mechanisms (specifically, _Facebook_, _Google_, _Amazon_, or _Sign in with Apple_), you will also need to enter your _App ID_, _App Secret_, and redirect URLs. 6. (Optional) Add multi-factor authentication (MFA). MFA is set to **Off** by default. To turn on MFA, do the following in the **Multi-factor authentication** section: * Choose **Enforced** to require MFA for all users or choose **Optional** to allow individual users to enable MFA. * (Optional) Choose **SMS**, and enter your SMS message. -* (Optional) Choose **Authenticator Application** if you want your app to load with an authentication flow that includes sign up and sign in. -7. In the **Configure sign up** section, expand **Password protection settings** and customize the password policy settings to enforce. u6. Choose **Save and Deploy**. This starts a CloudFormation deployment with the progress displayed in the upper right corner of the page. -8. After creating and configuring your auth resources, you'll need to pull them down from Amplify Studio. To do so, simply click on "Local setup instructions" in the upper right hand corner of the Studio console and execute the CLI command it provides at the root directory of your app. +* (Optional) Choose **Authenticator Application** if you want your app to load with an authentication flow that includes sign-up and sign-in. +7. In the **Configure sign-up** section, expand **Password protection settings** and customize the password policy settings to enforce. Choose **Save and Deploy**. This starts a CloudFormation deployment with the progress displayed in the upper right corner of the page. +8. After creating and configuring your auth resources, you will need to pull them down from Amplify Studio. To do so, simply select "Local setup instructions" in the upper right-hand corner of the Studio console and run the CLI command it provides at the root directory of your app. > You can also [import](https://docs.amplify.aws/console/auth/import/) existing Amazon Cognito resources and [manage users and groups](https://docs.amplify.aws/console/auth/user-management/) through the Amplify Studio UI. @@ -189,9 +189,9 @@ Amplify Studio allows you create auth resources, set up authorization rules, imp -Existing Authentication resources from AWS (e.g. Amazon Cognito UserPools or Identity Pools) can be used with the Amplify Libraries by calling the `Amplify.configure()` method. +Existing Authentication resources from AWS (such as Amazon Cognito User Pools or Identity Pools) can be used with the Amplify Libraries by calling the `Amplify.configure()` method. -In your app's entry point (i.e. **App.js**, **index.js**, **_app.js**, or **main.js**), import and load the configuration file: +In your app's entry point (specifically **App.js**, **index.js**, **_app.js**, or **main.js**), import and load the configuration file: ```javascript import { Amplify, Auth } from 'aws-amplify'; @@ -268,16 +268,16 @@ Amplify.configure({ const currentConfig = Auth.configure(); ``` -If your existing UserPool client has a required attribute that is NOT set to mutable, you may face login issues when using Social sign-in. To resolve this, you will need to create a new UserPool client and mark the required attribute as mutable. +If your existing user pool client has a required attribute that is *not* set to mutable, you may face login issues when using social sign-in. To resolve this, you will need to create a new user pool client and mark the required attribute as mutable. #### OAuth configuration parameters: -These settings can be found in the Cognito User Pools console under **App Integration** section -- `domain`: This can be found in the **Domain name** sub section -- `scope`: Remember to have the scope allowed on the Cognito App client, this can be found on **App client settings** sub section -- `redirectSignIn`: URL must be present on **Callback URL(s)** , check on **App client settings** sub section -- `redirectSignOut`: URL must be present on **Sign out URL(s)**, check on **App client settings** sub section -- `responseType`: Option must be enabled on the App client, look for **Allowed OAuth Flows** on **App client settings** sub section. *Authorization code grant* is for 'code' value and *Implicit grant* is for 'token' value. +These settings can be found in the Cognito User Pools console under the **App Integration** section +- `domain`: This can be found in the **Domain name** subsection +- `scope`: Remember to have the scope allowed on the Cognito App client; this can be found in the **App client settings** subsection +- `redirectSignIn`: URL must be present on **Callback URL(s)**; check in the **App client settings** subsection +- `redirectSignOut`: URL must be present on **Sign out URL(s)**; check in the **App client settings** subsection +- `responseType`: Option must be enabled on the App client; look for **Allowed OAuth Flows** in the **App client settings** subsection. *Authorization code grant* is for 'code' value and *Implicit grant* is for 'token' value. @@ -291,23 +291,23 @@ Before you implement Auth on your frontend application, you will want to evaluat ### Compare implementation options -There are a few options to implement Auth depending on how much customization you will need: +There are a few options to implement Auth, depending on how much customization you will need: | | Amplify Authenticator | Amplify Libraries | |:--|:--|:--| | **Description** | Open source drop-in UI component for authentication | Low-level building blocks for implementing authentication | | **Benefits** | Automatically integrates with your existing Amplify configuration and allows you to easily add the entire authentication flow to your application. You can then customize themes to adjust colors and styling as needed. | Gives you full control over the UI and logic implementation. | -| **Constraints** | Dependent on Amplify CLI for provisioning resources. | Requires the building of screens and frontend logic to enable the sign in and registration experiences. | +| **Constraints** | Dependent on Amplify CLI for provisioning resources. | Requires the building of screens and frontend logic to enable the sign-in and registration experiences. |
-We recommend using the Authenticator UI component for quick and easy set up and then use the Amplify Libraries to customize the user experience and logic as needed. Once you decide which option will work for your use case, you can continue implementing authentication on your frontend application. If you prefer to work directly with the APIs, you can review the [*Enable Sign-up, Sign-in, and Sign-out*](/lib/auth/emailpassword/q/platform/js/) guide. +We recommend using the Authenticator UI component for quick and easy setup and then use the Amplify Libraries to customize the user experience and logic as needed. Once you decide which option will work for your use case, you can continue implementing authentication on your frontend application. If you prefer to work directly with the APIs, you can review the [*Enable sign-up, sign-in, and sign-out*](/lib/auth/emailpassword/q/platform/js/) guide. ## Build an Authentication experience using the Authenticator -Creating the sign-in flow can be quite difficult and time consuming to get right. However, Amplify has the Authenticator UI component which you can use to quickly build the entire authentication flow for your app, using your backend configuration. +Creating the sign-in flow can be quite difficult and time-consuming to get right. However, Amplify has the Authenticator UI component which you can use to quickly build the entire authentication flow for your app, using your backend configuration. -Amplify has pre-built UI components for React, Vue, Angular, React Native, Swift, Android, and Flutter. In this guide we are focusing on those for web applications. +Amplify has pre-built UI components for React, Vue, Angular, React Native, Swift, Android, and Flutter. In this guide, we are focusing on those for web applications. @@ -322,7 +322,7 @@ Next, open __src/App.js__ and add the `withAuthenticator` component. **withAuthenticator** -The `withAuthenticator` is a higher-order component (HoC) that wraps `Authenticator`. You'll also notice the `user` and `signOut` are provided to the wrapped component. +The `withAuthenticator` is a higher-order component (HoC) that wraps `Authenticator`. You will also notice that `user` and `signOut` are provided to the wrapped component. **Usage** @@ -388,7 +388,7 @@ Next, open __src/App.js__ and add the `Authenticator` component. **Authenticator** -The `Authenticator` component offers a simple way to add authentication flows into your app. This component encapsulates an authentication workflow in the framework of your choice and is backed by the cloud resources set up in your Auth cloud resources. You’ll also notice that `user` and `signOut` are passed to the inner template. +The `Authenticator` component offers a simple way to add authentication flows into your app. This component encapsulates an authentication workflow in the framework of your choice and is backed by the cloud resources set up in your Auth cloud resources. You will also notice that `user` and `signOut` are passed to the inner template. ```html