From bcf4eb27f8616872cafcd1916f8fde32c01a9d67 Mon Sep 17 00:00:00 2001
From: Harshdeep Singh <6162866+harsh62@users.noreply.github.com>
Date: Fri, 10 May 2024 20:52:30 -0400
Subject: [PATCH 1/9] fix(swift): Fixing Auth category for Gen2
---
src/directory/directory.mjs | 6 +
.../external-identity-providers/index.mdx | 129 +++----
.../build-a-backend/auth/concepts/index.mdx | 8 +-
.../multi-factor-authentication/index.mdx | 359 +++++++++++++++++-
.../concepts/tokens-and-credentials/index.mdx | 8 +-
.../manage-user-attributes/index.mdx | 43 ++-
.../connect-your-frontend/sign-in/index.mdx | 52 ++-
.../connect-your-frontend/sign-out/index.mdx | 26 ++
.../connect-your-frontend/sign-up/index.mdx | 33 ++
.../switch-auth/index.mdx | 93 +++++
.../using-the-authenticator/index.mdx | 57 ++-
.../custom-auth-flows/index.mdx | 117 ------
.../auth/set-up-auth/index.mdx | 9 +-
.../build-a-backend/auth/using-sdk/index.mdx | 59 +++
14 files changed, 794 insertions(+), 205 deletions(-)
create mode 100644 src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
create mode 100644 src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs
index ef3a5e7fbc5..db025844e70 100644
--- a/src/directory/directory.mjs
+++ b/src/directory/directory.mjs
@@ -99,6 +99,9 @@ export const directory = {
{
path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx'
},
+ {
+ path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx'
+ },
{
path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-out/index.mdx'
},
@@ -167,6 +170,9 @@ export const directory = {
},
{
path: 'src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx'
+ },
+ {
+ path: 'src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx'
}
]
},
diff --git a/src/pages/[platform]/build-a-backend/auth/concepts/external-identity-providers/index.mdx b/src/pages/[platform]/build-a-backend/auth/concepts/external-identity-providers/index.mdx
index e4a22e1ff72..e8c05bdbc30 100644
--- a/src/pages/[platform]/build-a-backend/auth/concepts/external-identity-providers/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/concepts/external-identity-providers/index.mdx
@@ -276,70 +276,8 @@ export const auth = defineAuth({
}
});
```
-
-[Learn more about configuring the React Authenticator component for external providers](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#external-providers)
-
-{/* @TODO refactor with connect-your-frontend/sign-in */}
-## Set up your frontend
-
-
-
-If you are using the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#external-providers) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
-
-
-
-Use the `signInWithRedirect` API to initiate sign-in with an external identity provider.
-
-```ts title="src/my-client-side-js.js"
-import { signInWithRedirect } from 'aws-amplify/auth';
-
-await signInWithRedirect({
- provider: 'Apple'
-});
-```
-
-
-
-
-### (Required for Multi-Page Applications) Complete external Sign In after Redirect
-
-If you are developing a multi-page application, and the redirected page is not the same page that initiated the sign in, you will need to add the following code to the redirected page to ensure the sign in gets completed:
-
-```ts title="src/my-redirected-page.ts"
-import 'aws-amplify/auth/enable-oauth-listener';
-import { getCurrentUser, fetchUserAttributes } from 'aws-amplify/auth';
-import { Hub } from 'aws-amplify/utils';
-
-Hub.listen("auth", ({ payload }) => {
- switch (payload.event) {
- case "signInWithRedirect":
- const user = await getCurrentUser();
- const userAttributes = await fetchUserAttributes();
- console.log({user, userAttributes});
- break;
- case "signInWithRedirect_failure":
- // handle sign in failure
- break;
- case "customOAuthState":
- const state = payload.data; // this will be customState provided on signInWithRedirect function
- console.log(state);
- break;
- }
-});
-```
-
-
-
-**Note:** The listener only works on the client side in the context of a SSR-enabled project, so ensure to import the listener on the client side only. For example, in a Next.js project, you should add the above import statement to a component that renders on the client side only by `'use client'`.
-
-
-
-
-
-When you import and use the `signInWithRedirect` function, it will add a listener as a side effect that will complete the external sign in when an end user is redirected back to your app. This works well in a single-page application but in a multi-page application, you might get redirected to a page that doesn't include the listener that was originally added as a side-effect. Hence you must include the specific OAuth listener on your login success page.
-
-
+- [Learn more about configuring the React Authenticator component for external providers](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#external-providers)
## Configure OIDC provider
@@ -429,6 +367,69 @@ await signInWithRedirect({
```
+
+{/* @TODO refactor with connect-your-frontend/sign-in */}
+## Set up your frontend
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration#external-providers) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+Use the `signInWithRedirect` API to initiate sign-in with an external identity provider.
+
+```ts title="src/my-client-side-js.js"
+import { signInWithRedirect } from 'aws-amplify/auth';
+
+await signInWithRedirect({
+ provider: 'Apple'
+});
+```
+
+
+
+
+### (Required for Multi-Page Applications) Complete external Sign In after Redirect
+
+If you are developing a multi-page application, and the redirected page is not the same page that initiated the sign in, you will need to add the following code to the redirected page to ensure the sign in gets completed:
+
+```ts title="src/my-redirected-page.ts"
+import 'aws-amplify/auth/enable-oauth-listener';
+import { getCurrentUser, fetchUserAttributes } from 'aws-amplify/auth';
+import { Hub } from 'aws-amplify/utils';
+
+Hub.listen("auth", ({ payload }) => {
+ switch (payload.event) {
+ case "signInWithRedirect":
+ const user = await getCurrentUser();
+ const userAttributes = await fetchUserAttributes();
+ console.log({user, userAttributes});
+ break;
+ case "signInWithRedirect_failure":
+ // handle sign in failure
+ break;
+ case "customOAuthState":
+ const state = payload.data; // this will be customState provided on signInWithRedirect function
+ console.log(state);
+ break;
+ }
+});
+```
+
+
+
+**Note:** The listener only works on the client side in the context of a SSR-enabled project, so ensure to import the listener on the client side only. For example, in a Next.js project, you should add the above import statement to a component that renders on the client side only by `'use client'`.
+
+
+
+
+
+When you import and use the `signInWithRedirect` function, it will add a listener as a side effect that will complete the external sign in when an end user is redirected back to your app. This works well in a single-page application but in a multi-page application, you might get redirected to a page that doesn't include the listener that was originally added as a side-effect. Hence you must include the specific OAuth listener on your login success page.
+
+
+
+
## Next steps
-- [Learn how to sign in with external providers](/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/#sign-in-with-external-provider)
+- [Learn how to sign in with external providers](/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/#sign-in-with-an-external-identity-provider)
diff --git a/src/pages/[platform]/build-a-backend/auth/concepts/index.mdx b/src/pages/[platform]/build-a-backend/auth/concepts/index.mdx
index 2a919eae28e..45c6475d4b4 100644
--- a/src/pages/[platform]/build-a-backend/auth/concepts/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/concepts/index.mdx
@@ -35,12 +35,12 @@ export function getStaticProps() {
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 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 external 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 external provider such as Apple, 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:
-- external provider federation which enables easier access for your users but shares data with third parties.
+- External provider federation which enables easier access for your users but shares data with third parties.
You can improve security credentials and verification for these authentication methods by:
@@ -55,7 +55,7 @@ Amplify Auth is powered by [Amazon Cognito](https://aws.amazon.com/cognito/). Am
1. [Amazon Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) is a full-featured user directory service to handle user registration, authentication, and account recovery
2. [Amazon Cognito Federated Identities or Identity Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) is a service used to authorize your users to interact with other AWS services
-Amplify interfaces with User Pools to store your user information, including federation with other OpenID providers like Facebook and Google, and leverages federated identities to manage user access to AWS resources.
+Amplify interfaces with User Pools to store your user information, including federation with other OpenID providers like Apple, Facebook, Google, or Amazon, and leverages federated identities to manage user access to AWS resources.
Authorization is often done in one of two ways:
@@ -72,7 +72,7 @@ Amazon Cognito can be customized based on your security strategy for authenticat
- 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** with phone number for all users, you will need to include MFA setup (i.e. mandating phone number) when users sign up.
Visit 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).
diff --git a/src/pages/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/index.mdx b/src/pages/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/index.mdx
index 0eda0407ce2..810bc7c43f6 100644
--- a/src/pages/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/index.mdx
@@ -43,14 +43,14 @@ export const auth = defineAuth({
},
// highlight-start
multifactor: {
- mode: 'optional',
+ mode: 'OPTIONAL',
totp: true
}
// highlight-end
});
```
-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.
+When multi-factor authentication (MFA) is REQUIRED with SMS in your backend auth resource, you will need to pass the phone number during sign-up API call. If you are using the `email` or `username` as the primary sign-in mechanism, you will need to pass the `phone_number` attribute as a user attribute. This will change depending on if you enable SMS, TOTP, or both. Visit the [multi-factor authentication documentation](/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/) to learn more about enabling MFA on your backend auth resource.
### Understand your MFA options
@@ -70,12 +70,37 @@ When enabling MFA you will have two key decisions to make:
## Multi-factor authentication with SMS
-
+
If you are using the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/swift/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/flutter/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/android/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
Once you have setup SMS as your second layer of authentication with MFA as shown above, your users will get an authentication code via a text message to complete sign-in after they sign in with their username and password.
@@ -92,6 +117,7 @@ Once you have setup SMS as your second layer of authentication with MFA as shown
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.
+
```ts
import { signUp } from 'aws-amplify/auth';
@@ -106,9 +132,36 @@ await signUp({
},
});
```
+
+
+```swift
+func signUp(username: String, password: String, email: String, phonenumber: String) async {
+ do {
+ let signUpResult = try await Amplify.Auth.signUp(
+ username: username,
+ password: password,
+ options: .init(userAttributes: [
+ AuthUserAttribute(.email, value: email),
+ AuthUserAttribute(.phoneNumber, value: phonenumber)
+ ])
+ )
+ if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
+ print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
+ } else {
+ print("SignUp Complete")
+ }
+ } catch let error as AuthError {
+ print("An error occurred while registering a user \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+```
+
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.
+
```ts
import { confirmSignUp } from 'aws-amplify/auth';
@@ -117,6 +170,26 @@ await confirmSignUp({
confirmationCode: "123456",
})
```
+
+
+
+
+```swift
+func confirmSignUp(for username: String, with confirmationCode: String) async {
+ do {
+ let confirmSignUpResult = try await Amplify.Auth.confirmSignUp(
+ for: username,
+ confirmationCode: confirmationCode
+ )
+ print("Confirm sign up result completed: \(confirmSignUpResult.isSignUpComplete)")
+ } catch let error as AuthError {
+ print("An error occurred while confirming sign up \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+```
+
### Manage SMS MFA during sign-in
@@ -124,6 +197,7 @@ After a user signs in, if they have MFA enabled for their account, a challenge w
If MFA is **ON** or enabled for the user, you must call `confirmSignIn` with the OTP sent to their phone.
+
```ts
import { confirmSignIn } from 'aws-amplify/auth';
@@ -131,27 +205,90 @@ await confirmSignIn({
challengeResponse: "123456"
});
```
+
+
+
+
+```swift
+func confirmSignIn() async {
+ do {
+ let signInResult = try await Amplify.Auth.confirmSignIn(
+ challengeResponse: "")
+ print("Confirm sign in succeeded. Next step: \(signInResult.nextStep)")
+ } catch let error as AuthError {
+ print("Confirm sign in failed \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+```
+
After a user has been signed in, 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.
+
```ts
import { updateMFAPreference } from 'aws-amplify/auth';
await updateMFAPreference({ sms: 'PREFERRED' });
```
+
+
+
+
+```swift
+func updateMFAPreferences() async throws {
+ let authCognitoPlugin = try Amplify.Auth.getPlugin(
+ for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
+
+ let smsMfaPreference: MFAPreference = .preferred
+
+ try await authCognitoPlugin?.updateMFAPreference(
+ sms: smsMfaPreference)
+}
+```
+
## Multi-factor authentication with TOTP
+
If you are using the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/swift/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/flutter/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
+
+
+
+
+If you are using the [Authenticator component](https://ui.docs.amplify.aws/android/connected-components/authenticator) with Amplify, this feature works without any additional code. The guide below is for writing your own implementation.
+
+
+
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, 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.
### Set up TOTP for a user
+
+
After you initiate a user sign in with the `signIn` API where a user is required to set up TOTP as an MFA method, the API call will return `CONTINUE_SIGN_IN_WITH_TOTP_SETUP` 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 your user pool.
@@ -182,9 +319,53 @@ switch (nextStep.signInStep) {
// ...
}
```
+
+
+
+
+After you initiate a user sign in with the `signIn` API where a user is required to set up TOTP as an MFA method, the API call will return `continueSignInWithTOTPSetup` 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 your user pool.
+- TOTP is enabled in your user pool.
+- User does not have TOTP MFA set up already.
+
+The `continueSignInWithTOTPSetup` step signifies that the user must set up TOTP before they can sign in. The step returns an associated value of type `TOTPSetupDetails` which must be used to configure an authenticator app like Microsoft Authenticator or Google Authenticator. `TOTPSetupDetails` provides a helper method called `getSetupURI` which generates a URI that can be used, for example, in a button to open the user's installed authenticator app. For more advanced use cases, `TOTPSetupDetails` also contains a `sharedSecret` 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 can generate a TOTP code and provide it to the library to complete the sign in process.
+```swift
+func signIn(username: String, password: String) async {
+ do {
+ let signInResult = try await Amplify.Auth.signIn(
+ username: username,
+ password: password
+ )
+
+ if case .continueSignInWithTOTPSetup(let setUpDetails) = signInResult.nextStep {
+
+ print("Received next step as continue sign in by setting up TOTP")
+ print("Shared secret that will be used to set up TOTP in the authenticator app \(setUpDetails.sharedSecret)")
+
+ // appName parameter will help distinguish the account in the Authenticator app
+ let setupURI = try setUpDetails.getSetupURI(appName: ">")
+
+ print("TOTP Setup URI: \(setupURI)")
+
+ // Prompt the user to enter the TOTP code generated in their authenticator app
+ // Then invoke `confirmSignIn` api with the code
+
+ }
+ } catch let error as AuthError {
+ print("Sign in failed \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+```
+
The TOTP code can be obtained from the user via a text field or any other means. Once the user provides the TOTP code, call `confirmSignIn` with the TOTP code as the `challengeResponse` parameter.
+
```ts
import { confirmSignIn } from 'aws-amplify/auth';
@@ -192,14 +373,47 @@ await confirmSignIn({
challengeResponse: "123456"
});
```
+
+
+
+```swift
+func confirmSignIn() async {
+ do {
+ let signInResult = try await Amplify.Auth.confirmSignIn(
+ challengeResponse: "")
+ print("Confirm sign in succeeded. Next step: \(signInResult.nextStep)")
+ } catch let error as AuthError {
+ print("Confirm sign in failed \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+```
+
After a user has been signed in, 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.
+
```ts
import { updateMFAPreference } from 'aws-amplify/auth';
await updateMFAPreference({ totp: 'PREFERRED' });
```
+
+
+
+```swift
+func updateMFAPreferences() async throws {
+ let authCognitoPlugin = try Amplify.Auth.getPlugin(
+ for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
+
+ let totpMfaPreference: MFAPreference = .preferred
+
+ try await authCognitoPlugin?.updateMFAPreference(
+ totp: totpMfaPreference)
+}
+```
+
### Enable TOTP after a user is signed in
@@ -214,6 +428,7 @@ Invoke the `setUpTOTP` API to generate a `TOTPSetupDetails` object which should
that contains the `sharedSecret` which will be used to either to generate a QR code or can be manually entered into an Authenticator app.
+
```ts
import { setUpTOTP } from 'aws-amplify/auth';
@@ -222,22 +437,79 @@ const appName = 'my_app_name';
const setupUri = totpSetupDetails.getSetupUri(appName);
// Open setupUri with an authenticator APP to retrieve an OTP code
```
+
+
+
+```swift
+func setUpTOTP() async {
+ do {
+ let setUpDetails = try await Amplify.Auth.setUpTOTP()
+
+ print("Received next step as continue sign in by setting up TOTP")
+ print("Shared secret that will be used to set up TOTP in the authenticator app \(setUpDetails.sharedSecret)")
+
+ // appName parameter will help distinguish the account in the Authenticator app
+ let setupURI = try setUpDetails.getSetupURI(appName: ">")
+
+ print("TOTP Setup URI: \(setupURI)")
+
+ // Prompt the user to enter the TOTP code generated in their authenticator app
+ // Then invoke `confirmSignIn` api with the code
+ } catch {
+ print("TOTP Setup Initiation failed \(error)")
+ }
+}
+```
+
Once the Authenticator app is set up, the user must generate a TOTP code and provide it to the library. Pass the code to `verifyTOTPSetup` to complete the TOTP setup process.
+
```ts
import { verifyTOTPSetup } from 'aws-amplify/auth';
await verifyTOTPSetup({ code: "123456" });
```
+
+
+
+```swift
+func verifyTOTPSetup(totpCodeFromAuthenticatorApp: String) async {
+ do {
+ try await Amplify.Auth.verifyTOTPSetup(
+ code: totpCodeFromAuthenticatorApp)
+ } catch {
+ print("TOTP Setup Verification failed \(error)")
+ }
+}
+```
+
After TOTP setup is complete, 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.
+
```ts
import { updateMFAPreference } from 'aws-amplify/auth';
await updateMFAPreference({ sms: 'ENABLED', totp: 'PREFERRED' });
```
+
+
+
+```swift
+func updateMFAPreferences() async throws {
+ let authCognitoPlugin = try Amplify.Auth.getPlugin(
+ for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
+
+ let smsMfaPreference: MFAPreference = .enabled
+ let totpMfaPreference: MFAPreference = .preferred
+
+ try await authCognitoPlugin?.updateMFAPreference(
+ sms: smsMfaPreference,
+ totp: totpMfaPreference)
+}
+```
+
### Recover from a lost TOTP device
@@ -255,11 +527,27 @@ In a scenario where MFA is marked as "Required" in the Cognito User Pool and ano
Invoke the following API to get the current MFA preference and enabled MFA types, if any, for the current user.
+
```ts
import { fetchMFAPreference } from 'aws-amplify/auth';
const { enabled, preferred } = await fetchMFAPreference();
```
+
+
+
+```swift
+func getMFAPreferences() async throws {
+ let authCognitoPlugin = try Amplify.Auth.getPlugin(
+ for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
+
+ let result = try await authCognitoPlugin?.fetchMFAPreference()
+
+ print("Enabled MFA types: \(result?.enabled)")
+ print("Preferred MFA type: \(result?.preferred)")
+}
+```
+
### Update the current user's MFA preferences
@@ -271,12 +559,31 @@ Only one MFA method can be marked as preferred at a time. If the user has multip
+
```ts
import { updateMFAPreference } from 'aws-amplify/auth';
await updateMFAPreference({ sms: 'ENABLED', totp: 'PREFERRED' });
```
+
+
+```swift
+func updateMFAPreferences() async throws {
+ let authCognitoPlugin = try Amplify.Auth.getPlugin(
+ for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
+
+ let smsMfaPreference: MFAPreference = .enabled
+ let totpMfaPreference: MFAPreference = .preferred
+
+ try await authCognitoPlugin?.updateMFAPreference(
+ sms: smsMfaPreference,
+ totp: totpMfaPreference)
+}
+```
+
+
+
If multiple MFA methods are enabled for the user, the `signIn` API will return `CONTINUE_SIGN_IN_WITH_MFA_SELECTION` as the next step in the auth flow. During this scenario, the user should be prompted to select the MFA method they want to use to sign in and their preference should be passed to `confirmSignIn`.
```ts
@@ -316,6 +623,52 @@ async function handleMFASelection(mfaType: 'SMS' | 'TOTP') {
}
}
```
+
+
+
+
+If multiple MFA methods are enabled for the user, the `signIn` API will return `continueSignInWithMFASelection` as the next step in the auth flow. During this scenario, the user should be prompted to select the MFA method they want to use to sign in and their preference should be passed to `confirmSignIn`.
+
+```swift
+func signIn(username: String, password: String) async {
+ do {
+ let signInResult = try await Amplify.Auth.signIn(username: username, password: password)
+ switch signInResult.nextStep {
+
+ case .continueSignInWithMFASelection(let allowedMFATypes):
+ print("Received next step as continue sign in by selecting MFA type")
+ print("Allowed MFA types \(allowedMFATypes)")
+
+ // Prompt the user to select the MFA type they want to use
+ // Then invoke `confirmSignIn` api with the MFA type
+
+ default:
+
+ // Use has successfully signed in to the app
+ print("Step: \(signInResult.nextStep)")
+ }
+ } catch let error as AuthError{
+ print ("Sign in failed \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+
+func confirmSignInWithTOTPAsMFASelection() async {
+ do {
+ let signInResult = try await Amplify.Auth.confirmSignIn(
+ challengeResponse: MFAType.totp.challengeResponse)
+
+ if case .confirmSignInWithTOTPCode = signInResult.nextStep {
+ print("Received next step as confirm sign in with TOTP")
+ }
+
+ } catch {
+ print("Confirm sign in failed \(error)")
+ }
+}
+```
+
## Remember a device
diff --git a/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx b/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
index e082ebe3152..990f930a7a4 100644
--- a/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
@@ -253,8 +253,14 @@ class InMemoryStorage implements SecureStorageInterface {
## Token Revocation
-
+
Token revocation is enabled automatically in Amplify Auth. To revoke tokens you can set up global sign-out with `signOut({ global: true })` to globally sign out your user from all of their devices.
+
+
+
+Token revocation is enabled automatically in Amplify Auth. To revoke tokens you can set up global sign-out with `await Amplify.Auth.signOut(options: .init(globalSignOut: true))` to globally sign out your user from all of their devices.
+
+
## Next steps
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx
index a300bf58439..7de885f7164 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx
@@ -54,7 +54,7 @@ await signUp({
```
-
+
### Configure custom user attributes during sign-up
Custom attributes can be passed in with the `userAttributes` option of the `signUp` API:
@@ -101,6 +101,33 @@ Future _signUp({
}
```
+
+
+
+```swift
+func signUp(username: String, password: String, email: String, phonenumber: String) async {
+ do {
+ let signUpResult = try await Amplify.Auth.signUp(
+ username: username,
+ password: password,
+ options: .init(userAttributes: [
+ AuthUserAttribute(.email, value: email),
+ AuthUserAttribute(.custom("my-custom-attribute"), value: )
+ ])
+ )
+ if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
+ print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
+ } else {
+ print("SignUp Complete")
+ }
+ } catch let error as AuthError {
+ print("An error occurred while registering a user \(error)")
+ } catch {
+ print("Unexpected error: \(error)")
+ }
+}
+```
+
### Retrieve user attributes
@@ -583,7 +610,13 @@ RxAmplify.Auth.updateUserAttributes(attributes)
### Verify user attribute
+
Some attributes require confirmation for the attribute update to complete. If the attribute needs to be confirmed, part of the result of the `updateUserAttribute` or `updateUserAttributes` APIs will be `CONFIRM_ATTRIBUTE_WITH_CODE`. A confirmation code will be sent to the delivery medium mentioned in the delivery details. When the user gets the confirmation code, you can present a UI to the user to enter the code and invoke the `confirmUserAttribute` API with their input:
+
+
+
+Some attributes require confirmation for the attribute update to complete. If the attribute needs to be confirmed, part of the result of the `updateUserAttribute` or `updateUserAttributes` APIs will be `confirmAttributeWithCode`. A confirmation code will be sent to the delivery medium mentioned in the delivery details. When the user gets the confirmation code, you can present a UI to the user to enter the code and invoke the `confirmUserAttribute` API with their input:
+
```typescript
@@ -742,9 +775,9 @@ async function handleSendUserAttributeVerificationCode(
```swift
-func resendCode() async {
+func sendVerificationCode() async {
do {
- let deliveryDetails = try await Amplify.Auth.resendConfirmationCode(forUserAttributeKey: .email)
+ let deliveryDetails = try await Amplify.Auth.sendVerificationCode(forUserAttributeKey: .email)
print("Resend code send to - \(deliveryDetails)")
} catch let error as AuthError {
print("Resend code failed with error \(error)")
@@ -759,9 +792,9 @@ func resendCode() async {
```swift
-func resendCode() -> AnyCancellable {
+func sendVerificationCode() -> AnyCancellable {
Amplify.Publisher.create {
- try await Amplify.Auth.resendConfirmationCode(forUserAttributeKey: .email)
+ try await Amplify.Auth.sendVerificationCode(forUserAttributeKey: .email)
}.sink {
if case let .failure(authError) = $0 {
print("Resend code failed with error \(authError)")
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
index 32ca7334503..1e03eaf75ef 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
@@ -30,11 +30,37 @@ export function getStaticProps() {
Amplify provides a client library that enables you to interact with backend resources such as Amplify Auth.
+
The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/swift/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/flutter/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/android/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
## Using the signIn API
@@ -185,7 +211,7 @@ func signIn(username: String, password: String) async {
let signInResult = try await Amplify.Auth.signIn(
username: username,
password: password
- )
+ )
if signInResult.isSignedIn {
print("Sign in succeeded")
}
@@ -206,7 +232,7 @@ func signIn(username: String, password: String) -> AnyCancellable {
try await Amplify.Auth.signIn(
username: username,
password: password
- )
+ )
}.sink {
if case let .failure(authError) = $0 {
print("Sign in failed \(authError)")
@@ -227,6 +253,7 @@ func signIn(username: String, password: String) -> AnyCancellable {
The `signIn` API response will include a `nextStep` property, which can be used to determine if further action is required. It may return the following next steps:
+
- `CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED` - The user was created with a temporary password and must set a new one. Complete the process with `confirmSignIn`.
- `CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE` - The sign-in must be confirmed with a custom challenge response. Complete the process with `confirmSignIn`.
- `CONFIRM_SIGN_IN_WITH_TOTP_CODE` - The sign-in must be confirmed with a TOTP code from the user. Complete the process with `confirmSignIn`.
@@ -236,6 +263,19 @@ The `signIn` API response will include a `nextStep` property, which can be used
- `RESET_PASSWORD` - The user must reset their password via `resetPassword`.
- `CONFIRM_SIGN_UP` - The user hasn't completed the sign-up flow fully and must be confirmed via `confirmSignUp`.
- `DONE` - The sign in process has been completed.
+
+
+
+- `confirmSignInWithNewPassword` - The user was created with a temporary password and must set a new one. Complete the process with `confirmSignIn`.
+- `confirmSignInWithCustomChallenge` - The sign-in must be confirmed with a custom challenge response. Complete the process with `confirmSignIn`.
+- `confirmSignInWithTOTPCode` - The sign-in must be confirmed with a TOTP code from the user. Complete the process with `confirmSignIn`.
+- `continueSignInWithTOTPSetup` - The TOTP setup process must be continued. Complete the process with `confirmSignIn`.
+- `confirmSignInWithSMSMFACode` - The sign-in must be confirmed with a SMS code from the user. Complete the process with `confirmSignIn`.
+- `continueSignInWithMFASelection` - The user must select their mode of MFA verification before signing in. Complete the process with `confirmSignIn`.
+- `resetPassword` - The user must reset their password via `resetPassword`.
+- `confirmSignUp` - The user hasn't completed the sign-up flow fully and must be confirmed via `confirmSignUp`.
+- `done` - The sign in process has been completed.
+
For more information on handling the TOTP and MFA steps that may be returned, see [multi-factor authentication](/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/).
@@ -337,7 +377,7 @@ export default function App() {
{/* with multi-factor auth */}
## With multi-factor auth enabled
-When multi-factor authentication (MFA) is enabled in your backend auth resource, you will also need to include MFA details when users sign up. This will change depending on if you enable SMS, TOTP, or both. Visit the [multi-factor authentication documentation](/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/) to learn more about enabling MFA on your backend auth resource.
+When multi-factor authentication (MFA) is REQUIRED with SMS in your backend auth resource, you will need to pass the phone number during sign-up API call. If you are using the `email` or `username` as the primary sign-in mechanism, you will need to pass the `phone_number` attribute as a user attribute. This will change depending on if you enable SMS, TOTP, or both. Visit the [multi-factor authentication documentation](/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/) to learn more about enabling MFA on your backend auth resource.
@@ -483,7 +523,13 @@ func signUp(username: String, password: String, email: String, phonenumber: Stri
+
You will then confirm sign-up, sign in, and receive a `nextStep` in the sign-in result of type `CONFIRM_SIGN_IN_WITH_SMS_MFA_CODE`. A confirmation code will also be texted to the phone number provided above. Pass the code you received to the `confirmSignIn` API:
+
+
+
+You will then confirm sign-up, sign in, and receive a `nextStep` in the sign-in result of type `confirmSignInWithSMSMFACode`. A confirmation code will also be texted to the phone number provided above. Pass the code you received to the `confirmSignIn` API:
+
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-out/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-out/index.mdx
index 249805d3c9d..8a5e0197f3a 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-out/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-out/index.mdx
@@ -30,11 +30,37 @@ export function getStaticProps() {
Amplify provides a client library that enables you to interact with backend resources such as Amplify Auth.
+
The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/swift/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/flutter/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/android/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
{/* signOut api definition */}
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-up/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-up/index.mdx
index 72b0b5bd3be..45056d61d69 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-up/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-up/index.mdx
@@ -32,11 +32,37 @@ Amplify provides a client library that enables you to interact with backend reso
{/* signUp api definition */}
+
The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/swift/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/flutter/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/android/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
To get started, you can use the `signUp()` API to create a new user in your backend:
@@ -259,9 +285,16 @@ func signUp(username: String, password: String, email: String, phonenumber: Stri
The `signUp` API response will include a `nextStep` property, which can be used to determine if further action is required. It may return the following next steps:
+
- `CONFIRM_SIGN_UP` - The sign up needs to be confirmed by collecting a code from the user and calling `confirmSignUp`.
- `DONE` - The sign up process has been fully completed.
- `COMPLETE_AUTO_SIGN_IN` - The sign up process needs to complete by invoking the `autoSignIn` API.
+
+
+
+- `confirmUser` - The sign up needs to be confirmed by collecting a code from the user and calling `confirmSignUp` API.
+- `done` - The sign up process has been fully completed.
+
## Confirm sign-up
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
new file mode 100644
index 00000000000..4feaad1d389
--- /dev/null
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
@@ -0,0 +1,93 @@
+import { getCustomStaticPath } from '@/utils/getCustomStaticPath';
+
+export const meta = {
+ title: 'Switching authentication flows',
+ description: 'Learn how to switch between different auth flows',
+ platforms: [
+ 'swift',
+ ]
+};
+
+export function getStaticPaths() {
+ return getCustomStaticPath(meta.platforms);
+}
+
+export function getStaticProps() {
+ return {
+ props: {
+ meta,
+ }
+ };
+}
+
+`AWSCognitoAuthPlugin` allows you to switch between different auth flows while initiating signIn. You can configure the flow in the `amplifyconfiguration.json` file or pass the `authFlowType` as a runtime parameter to the `signIn` api call.
+
+For client side authentication there are four different flows that can be configured during runtime:
+
+1. `userSRP`: The `userSRP` flow uses the [SRP protocol (Secure Remote Password)](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol) where the password never leaves the client and is unknown to the server. This is the recommended flow and is used by default.
+
+2. `userPassword`: The `userPassword` flow will send user credentials unencrypted to the back-end. If you want to migrate users to Cognito using the "Migration" trigger and avoid forcing users to reset their passwords, you will need to use this authentication type because the Lambda function invoked by the trigger needs to verify the supplied credentials.
+
+3. `customWithSRP`: The `customWithSRP` flow is used to start with SRP authentication and then switch to custom authentication. This is useful if you want to use SRP for the initial authentication and then use custom authentication for subsequent authentication attempts.
+
+4. `customWithoutSRP`: The `customWithoutSRP` flow is used to start authentication flow **WITHOUT** SRP and then use a series of challenge and response cycles that can be customized to meet different requirements.
+
+`Auth` can be configured to use the different flows at runtime by calling `signIn` with `AuthSignInOptions`'s `authFlowType` as `AuthFlowType.userPassword`, `AuthFlowType.customAuthWithoutSrp` or `AuthFlowType.customAuthWithSrp`. If you do not specify the `AuthFlowType` in `AuthSignInOptions`, the default flow (`AuthFlowType.userSRP`) will be used.
+
+
+
+Runtime configuration will take precedence and will override any auth flow type configuration present in amplifyconfiguration.json
+
+
+
+> For more information about authentication flows, please visit [AWS Cognito developer documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-custom-authentication-flow)
+
+## USER_PASSWORD_AUTH flow
+
+A use case for the `USER_PASSWORD_AUTH` authentication flow is migrating users into Amazon Cognito
+
+A user migration Lambda trigger helps migrate users from a legacy user management system into your user pool. If you choose the USER_PASSWORD_AUTH authentication flow, users don't have to reset their passwords during user migration. This flow sends your user's password to the service over an encrypted SSL connection during authentication.
+
+When you have migrated all your users, switch flows to the more secure SRP flow. The SRP flow doesn't send any passwords over the network.
+
+```swift
+func signIn(username: String, password: String) async throws {
+
+ let option = AWSAuthSignInOptions(authFlowType: .userPassword)
+ do {
+ let result = try await Amplify.Auth.signIn(
+ username: username,
+ password: password,
+ options: AuthSignInRequest.Options(pluginOptions: option))
+ print("Sign in succeeded with result: \(result)")
+ } catch {
+ print("Failed to sign in with error: \(error)")
+ }
+}
+```
+
+### Setup auth backend
+
+In order to use the authentication flow `USER_PASSWORD_AUTH`, your Cognito app client has to be configured to allow it. In the AWS Console, this is done by ticking the checkbox at General settings > App clients > Show Details (for the affected client) > Enable username-password (non-SRP) flow. If you're using the AWS CLI or CloudFormation, update your app client by adding `USER_PASSWORD_AUTH` to the list of "Explicit Auth Flows".
+
+### Migrate users with Amazon Cognito
+
+Amazon Cognito provides a trigger to migrate users from your existing user directory seamlessly into Cognito. You achieve this by configuring your User Pool's "Migration" trigger which invokes a Lambda function whenever a user that does not already exist in the user pool authenticates, or resets their password.
+
+In short, the Lambda function will validate the user credentials against your existing user directory and return a response object containing the user attributes and status on success. An error message will be returned if an error occurs. There's a documentation [here](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-import-using-lambda.html) on how to set up this migration flow and more detailed instructions [here](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html#cognito-user-pools-lambda-trigger-syntax-user-migration) on how the lambda should handle request and response objects.
+
+## CUSTOM_AUTH flow
+
+Amazon Cognito User Pools supports customizing the authentication flow to enable custom challenge types, in addition to a password in order to verify the identity of users. The custom authentication flow is a series of challenge and response cycles that can be customized to meet different requirements. These challenge types may include CAPTCHAs or dynamic challenge questions.
+
+To define your challenges for custom authentication flow, you need to implement three Lambda triggers for Amazon Cognito.
+
+The flow is initiated by calling `signIn` with `AuthSignInOptions` configured with `AuthFlowType.customAuthWithSrp` OR `AuthFlowType.customAuthWithoutSrp`.
+
+Follow the instructions in [Custom Auth Sign In](/gen1/[platform]/build-a-backend/auth/sign-in-custom-flow/) to learn about how to integrate custom authentication flow in your application with the Auth APIs.
+
+
+
+For more information about working with Lambda Triggers for custom authentication challenges, please visit [Amazon Cognito Developer Documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html).
+
+
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
index c7a0a188cc4..7506fa58762 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
@@ -28,10 +28,63 @@ export function getStaticProps() {
};
}
-The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/swift/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+```swift
+import Amplify
+import Authenticator
+import AWSCognitoAuthPlugin
+import SwiftUI
+
+@main
+struct MyApp: App {
+ init() {
+ do {
+ try Amplify.add(plugin: AWSCognitoAuthPlugin())
+ try Amplify.configure()
+ } catch {
+ print("Unable to configure Amplify \(error)")
+ }
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ Authenticator { state in
+ VStack {
+ Text("Hello, \(state.user.username)")
+ Button("Sign out") {
+ Task {
+ await state.signOut()
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/flutter/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/android/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
+The quickest way to get started with Amplify Auth in your frontend application is with the [Authenticator component](https://ui.docs.amplify.aws/react/connected-components/authenticator), which provides a customizable UI and complete authentication flows.
+
+
```tsx title="src/App.tsx"
import { Authenticator } from '@aws-amplify/ui-react';
import { Amplify } from 'aws-amplify';
@@ -58,7 +111,9 @@ export default function App() {
The Authenticator component is automatically configured based on the outputs generated from your backend. To learn more about the Authenticator and how to customize its appearance, visit the [Amplify UI documentation](https://ui.docs.amplify.aws/).
+
Conversely, you can bring your own UI and leverage the library from [`aws-amplify`](https://www.npmjs.com/package/aws-amplify) to handle authentication flows manually.
+
{/* using the Authenticator Provider */}
{/* useAuthenticator */}
diff --git a/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx b/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx
index 0224b44a403..525fd1cf10a 100644
--- a/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/customize-auth-lifecycle/custom-auth-flows/index.mdx
@@ -60,123 +60,6 @@ For more information on adding capabilities to your application, see [Xcode Capa
The custom auth flow can be [configured manually](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html).
-## Register a user
-
-The flow as mentioned above requires a username and a valid email id as parameters to register a user. Invoke the following api to initiate a sign up flow.
-
-
-
-
-
-```swift
-func signUp(username: String, email: String) async {
- let userAttributes = [AuthUserAttribute(.email, value: email)]
- let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
- do {
- let signUpResult = try await Amplify.Auth.signUp(
- username: username,
- password: UUID().uuidString,
- options: options
- )
-
- if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
- print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
- } else {
- print("Signup Complete")
- }
- } catch let error as AuthError {
- print("An error occurred while registering a user \(error)")
- } catch {
- print("Unexpected error: \(error)")
- }
-}
-```
-
-
-
-
-
-```swift
-func signUp(username: String, password: String, email: String) -> AnyCancellable {
- let userAttributes = [AuthUserAttribute(.email, value: email)]
- let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
- let sink = Amplify.Publisher.create {
- try await Amplify.Auth.signUp(
- username: username,
- password: UUID().uuidString,
- options: options
- )
- }.sink {
- if case let .failure(authError) = $0 {
- print("An error occurred while registering a user \(authError)")
- }
- }
- receiveValue: { signUpResult in
- if case let .confirmUser(deliveryDetails, _, userId) = signUpResult.nextStep {
- print("Delivery details \(String(describing: deliveryDetails)) for userId: \(String(describing: userId)))")
- } else {
- print("Signup Complete")
- }
-
- }
- return sink
-}
-```
-
-
-
-
-
-The next step in the sign up flow is to confirm the user. A confirmation code will be sent to the email id provided during sign up. Enter the confirmation code received via email in the `confirmSignUp` call.
-
-
-
-
-
-```swift
-func confirmSignUp(for username: String, with confirmationCode: String) async {
- do {
- let confirmSignUpResult = try await Amplify.Auth.confirmSignUp(
- for: username,
- confirmationCode: confirmationCode
- )
- print("Confirm sign up result completed: \(confirmSignUpResult.isSignUpComplete)")
- } catch let error as AuthError {
- print("An error occurred while confirming sign up \(error)")
- } catch {
- print("Unexpected error: \(error)")
- }
-}
-```
-
-
-
-
-
-```swift
-func confirmSignUp(for username: String, with confirmationCode: String) -> AnyCancellable {
- Amplify.Publisher.create {
- try await Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode)
- }.sink {
- if case let .failure(authError) = $0 {
- print("An error occurred while confirming sign up \(authError)")
- }
- }
- receiveValue: { _ in
- print("Confirm signUp succeeded")
- }
-}
-```
-
-
-
-
-
-You will know the sign up flow is complete if you see the following in your console window:
-
-```console
-Confirm signUp succeeded
-```
## Sign in a user
Implement a UI to get the username from the user. After the user enters the username you can start the sign in flow by calling the following method:
diff --git a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx
index 300cb0dcf94..07616f7bdf5 100644
--- a/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/set-up-auth/index.mdx
@@ -608,22 +608,17 @@ Move the generated files to your project. You can do this by dragging and droppi
Open your project in Xcode and select File > Add Packages... and add the following dependencies:
-- Amplify Library for Swift: Enter its [GitHub URL](https://github.com/aws-amplify/amplify-swift), *select Up to Next Major Version* and click *Add Package*
+- Amplify Library for Swift: Enter its GitHub URL (https://github.com/aws-amplify/amplify-swift), *select Up to Next Major Version* and click *Add Package*
- Select the following libraries:
- Amplify
- AWSCognitoAuthPlugin
-- Amplify UI Swift - Authenticator: Enter its [GitHub URL](https://github.com/aws-amplify/amplify-ui-swift-authenticator), *select Up to Next Major Version* and click *Add Package*
+- Amplify UI Swift - Authenticator: Enter its GitHub URL (https://github.com/aws-amplify/amplify-ui-swift-authenticator), *select Up to Next Major Version* and click *Add Package*
- Select the following library:
- Authenticator
-Once you are done, add the API dependencies to your project. Select **File > Add Package Dependencies...** and add the `AWSAPIPlugin`.
-
-
-
-
Next, update the `init` part of your `MyAmplifyAppApp.swift` file with the following code:
```swift title="MyAmplifyApp.swift"
diff --git a/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx b/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
new file mode 100644
index 00000000000..062ba85940c
--- /dev/null
+++ b/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
@@ -0,0 +1,59 @@
+import { getCustomStaticPath } from '@/utils/getCustomStaticPath';
+
+export const meta = {
+ title: 'Use AWS SDK for Swift',
+ description: 'For advanced use cases where Amplify does not provide the functionality, you can retrieve the escape hatch to access the AWSCognito instance.',
+ platforms: [
+ 'swift' ],
+};
+
+export const getStaticPaths = async () => {
+ return getCustomStaticPath(meta.platforms);
+};
+
+export function getStaticProps(context) {
+ return {
+ props: {
+ platform: context.params.platform,
+ meta
+ }
+ };
+}
+
+
+For advanced use cases where Amplify does not provide the functionality, you can retrieve an escape hatch to access the underlying Amazon Cognito client.
+
+
+
+**Note:** While the Amplify Library for Swift is production ready, please note that the underlying AWS SDK for Swift is currently in Developer Preview, and is not yet intended for production workloads. [Here is additional reading material](https://github.com/awslabs/aws-sdk-swift/blob/main/Sources/Core/AWSSDKForSwift/Documentation.docc/stability.md) on the stability of the SDK.
+
+
+
+The escape hatch provides access to the underlying `AWSCognitoIdentityProvider` instance. Import the necessary types:
+
+```swift
+import AWSCognitoAuthPlugin
+import AWSCognitoIdentityProvider
+```
+
+Then retrieve the escape hatch with this code:
+
+```swift
+func getEscapeHatch() {
+ let client: CognitoIdentityProviderClient
+
+ // Get the instance of AWSCognitoAuthPlugin
+ let plugin = try? Amplify.Auth.getPlugin(for: "awsCognitoAuthPlugin") as? AWSCognitoAuthPlugin
+
+ // Get the instance of CognitoIdentityProviderClient
+ if case .userPoolAndIdentityPool(let userPoolClient, _) = plugin?.getEscapeHatch() {
+ client = userPoolClient
+ } else if case .userPool(let userPoolClient) = plugin?.getEscapeHatch() {
+ client = userPoolClient
+ } else {
+ fatalError("No user pool configuration found")
+ }
+ print("Fetched escape hatch - \(String(describing: client))")
+}
+```
+
From fb62ed964f72e393c9393895fcb4296196c0d018 Mon Sep 17 00:00:00 2001
From: Harsh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 10:25:29 -0400
Subject: [PATCH 2/9] Update
src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
Co-authored-by: Sebastian Villena <97059974+ruisebas@users.noreply.github.com>
---
.../auth/concepts/tokens-and-credentials/index.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx b/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
index 990f930a7a4..94d9510e539 100644
--- a/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/concepts/tokens-and-credentials/index.mdx
@@ -258,7 +258,7 @@ Token revocation is enabled automatically in Amplify Auth. To revoke tokens you
-Token revocation is enabled automatically in Amplify Auth. To revoke tokens you can set up global sign-out with `await Amplify.Auth.signOut(options: .init(globalSignOut: true))` to globally sign out your user from all of their devices.
+Token revocation is enabled automatically in Amplify Auth. To revoke tokens you can invoke `await Amplify.Auth.signOut(options: .init(globalSignOut: true))` to globally sign out your user from all of their devices.
From 5a01df9ad811e606e059d87ca1a8051e53e40e8d Mon Sep 17 00:00:00 2001
From: Harsh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 10:25:36 -0400
Subject: [PATCH 3/9] Update
src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
Co-authored-by: Sebastian Villena <97059974+ruisebas@users.noreply.github.com>
---
.../connect-your-frontend/using-the-authenticator/index.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
index 7506fa58762..52b84d52e94 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/using-the-authenticator/index.mdx
@@ -43,7 +43,7 @@ struct MyApp: App {
init() {
do {
try Amplify.add(plugin: AWSCognitoAuthPlugin())
- try Amplify.configure()
+ try Amplify.configure(with: .amplifyOutputs)
} catch {
print("Unable to configure Amplify \(error)")
}
From 57dc4aadb03247d545d13bc5d24d2a49dc68ea2c Mon Sep 17 00:00:00 2001
From: Harshdeep Singh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 10:28:27 -0400
Subject: [PATCH 4/9] working on review comments
---
.../auth/connect-your-frontend/manage-user-attributes/index.mdx | 2 +-
src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx
index 7de885f7164..fcf96aaf6ad 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/manage-user-attributes/index.mdx
@@ -105,7 +105,7 @@ Future _signUp({
```swift
-func signUp(username: String, password: String, email: String, phonenumber: String) async {
+func signUp(username: String, password: String, email: String) async {
do {
let signUpResult = try await Amplify.Auth.signUp(
username: username,
diff --git a/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx b/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
index 062ba85940c..5f892568d50 100644
--- a/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
@@ -1,7 +1,7 @@
import { getCustomStaticPath } from '@/utils/getCustomStaticPath';
export const meta = {
- title: 'Use AWS SDK for Swift',
+ title: 'Use AWS SDK',
description: 'For advanced use cases where Amplify does not provide the functionality, you can retrieve the escape hatch to access the AWSCognito instance.',
platforms: [
'swift' ],
From 504d0c6cebdbe93c357e7ddf14bc3ad9e63b6284 Mon Sep 17 00:00:00 2001
From: Harsh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 12:42:24 -0400
Subject: [PATCH 5/9] Update
src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
Co-authored-by: josef
---
.../auth/connect-your-frontend/sign-in/index.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
index 1e03eaf75ef..34abae81352 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx
@@ -377,7 +377,7 @@ export default function App() {
{/* with multi-factor auth */}
## With multi-factor auth enabled
-When multi-factor authentication (MFA) is REQUIRED with SMS in your backend auth resource, you will need to pass the phone number during sign-up API call. If you are using the `email` or `username` as the primary sign-in mechanism, you will need to pass the `phone_number` attribute as a user attribute. This will change depending on if you enable SMS, TOTP, or both. Visit the [multi-factor authentication documentation](/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/) to learn more about enabling MFA on your backend auth resource.
+When multi-factor authentication (MFA) is **required** with SMS in your backend auth resource, you will need to pass the phone number during sign-up API call. If you are using the `email` or `username` as the primary sign-in mechanism, you will need to pass the `phone_number` attribute as a user attribute. This will change depending on if you enable SMS, TOTP, or both. Visit the [multi-factor authentication documentation](/[platform]/build-a-backend/auth/concepts/multi-factor-authentication/) to learn more about enabling MFA on your backend auth resource.
From e2b532890f13527db563152516c9f8b639725bd3 Mon Sep 17 00:00:00 2001
From: Harsh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 12:43:02 -0400
Subject: [PATCH 6/9] Update
src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
Co-authored-by: josef
---
.../auth/connect-your-frontend/switch-auth/index.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
index 4feaad1d389..b980f6f951b 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
@@ -40,7 +40,7 @@ Runtime configuration will take precedence and will override any auth flow type
-> For more information about authentication flows, please visit [AWS Cognito developer documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-custom-authentication-flow)
+> For more information about authentication flows, please visit [Amazon Cognito developer documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-custom-authentication-flow)
## USER_PASSWORD_AUTH flow
From 24e8cb65e2d76693e54eebf14b133c3f846f0b87 Mon Sep 17 00:00:00 2001
From: Harshdeep Singh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 12:46:56 -0400
Subject: [PATCH 7/9] worked on review coments
---
src/directory/directory.mjs | 4 ++--
.../{switch-auth => switching-authentication-flows}/index.mdx | 4 ++--
.../build-a-backend/auth/{using-sdk => use-aws-sdk}/index.mdx | 3 ++-
3 files changed, 6 insertions(+), 5 deletions(-)
rename src/pages/[platform]/build-a-backend/auth/connect-your-frontend/{switch-auth => switching-authentication-flows}/index.mdx (98%)
rename src/pages/[platform]/build-a-backend/auth/{using-sdk => use-aws-sdk}/index.mdx (99%)
diff --git a/src/directory/directory.mjs b/src/directory/directory.mjs
index db025844e70..9c2b03b1983 100644
--- a/src/directory/directory.mjs
+++ b/src/directory/directory.mjs
@@ -100,7 +100,7 @@ export const directory = {
path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-in/index.mdx'
},
{
- path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx'
+ path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx'
},
{
path: 'src/pages/[platform]/build-a-backend/auth/connect-your-frontend/sign-out/index.mdx'
@@ -172,7 +172,7 @@ export const directory = {
path: 'src/pages/[platform]/build-a-backend/auth/advanced-workflows/index.mdx'
},
{
- path: 'src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx'
+ path: 'src/pages/[platform]/build-a-backend/auth/use-aws-sdk/index.mdx'
}
]
},
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
similarity index 98%
rename from src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
rename to src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
index 4feaad1d389..402d46252a4 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switch-auth/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
@@ -36,7 +36,7 @@ For client side authentication there are four different flows that can be config
-Runtime configuration will take precedence and will override any auth flow type configuration present in amplifyconfiguration.json
+Runtime configuration will take precedence and will override any auth flow type configuration present in amplify_outputs.json
@@ -66,7 +66,7 @@ func signIn(username: String, password: String) async throws {
}
```
-### Setup auth backend
+### Set up auth backend
In order to use the authentication flow `USER_PASSWORD_AUTH`, your Cognito app client has to be configured to allow it. In the AWS Console, this is done by ticking the checkbox at General settings > App clients > Show Details (for the affected client) > Enable username-password (non-SRP) flow. If you're using the AWS CLI or CloudFormation, update your app client by adding `USER_PASSWORD_AUTH` to the list of "Explicit Auth Flows".
diff --git a/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx b/src/pages/[platform]/build-a-backend/auth/use-aws-sdk/index.mdx
similarity index 99%
rename from src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
rename to src/pages/[platform]/build-a-backend/auth/use-aws-sdk/index.mdx
index 5f892568d50..777c899d688 100644
--- a/src/pages/[platform]/build-a-backend/auth/using-sdk/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/use-aws-sdk/index.mdx
@@ -4,7 +4,8 @@ export const meta = {
title: 'Use AWS SDK',
description: 'For advanced use cases where Amplify does not provide the functionality, you can retrieve the escape hatch to access the AWSCognito instance.',
platforms: [
- 'swift' ],
+ 'swift'
+ ],
};
export const getStaticPaths = async () => {
From d81a5a81d27dd930edb5833078405f4f0a932522 Mon Sep 17 00:00:00 2001
From: Harshdeep Singh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 16:15:12 -0400
Subject: [PATCH 8/9] update based on comments
---
.../switching-authentication-flows/index.mdx | 23 +++++++++++++++++--
1 file changed, 21 insertions(+), 2 deletions(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
index cc67657c187..6be3bce761c 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
@@ -68,13 +68,32 @@ func signIn(username: String, password: String) async throws {
### Set up auth backend
-In order to use the authentication flow `USER_PASSWORD_AUTH`, your Cognito app client has to be configured to allow it. In the AWS Console, this is done by ticking the checkbox at General settings > App clients > Show Details (for the affected client) > Enable username-password (non-SRP) flow. If you're using the AWS CLI or CloudFormation, update your app client by adding `USER_PASSWORD_AUTH` to the list of "Explicit Auth Flows".
+In order to use the authentication flow `USER_PASSWORD_AUTH`, your Cognito app client has to be configured to allow it. Amplify Gen 2 enables SRP auth by default. To enable USER_PASSWORD_AUTH, you can update the `backend.ts` file with the following changes:
+
+```ts title="amplify/backend.ts"
+import { defineBackend } from '@aws-amplify/backend'
+import { auth } from './auth/resource'
+import { data } from './data/resource'
+
+const backend = defineBackend({
+ auth,
+ data,
+});
+
+// highlight-start
+backend.auth.resources.cfnResources.cfnUserPoolClient.explicitAuthFlows = [
+ "ALLOW_USER_PASSWORD_AUTH",
+ "ALLOW_USER_SRP_AUTH",
+ "ALLOW_REFRESH_TOKEN_AUTH"
+];
+// highlight-end
+```
### Migrate users with Amazon Cognito
Amazon Cognito provides a trigger to migrate users from your existing user directory seamlessly into Cognito. You achieve this by configuring your User Pool's "Migration" trigger which invokes a Lambda function whenever a user that does not already exist in the user pool authenticates, or resets their password.
-In short, the Lambda function will validate the user credentials against your existing user directory and return a response object containing the user attributes and status on success. An error message will be returned if an error occurs. There's a documentation [here](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-import-using-lambda.html) on how to set up this migration flow and more detailed instructions [here](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html#cognito-user-pools-lambda-trigger-syntax-user-migration) on how the lambda should handle request and response objects.
+In short, the Lambda function will validate the user credentials against your existing user directory and return a response object containing the user attributes and status on success. An error message will be returned if an error occurs. There's documentation around [how to set up this migration flow](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-import-using-lambda.html) and more detailed instructions on [how the lambda should handle request and response objects]((https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html#cognito-user-pools-lambda-trigger-syntax-user-migration)).
## CUSTOM_AUTH flow
From f32188aad77d33b8469cc730873b6b1c91c071f1 Mon Sep 17 00:00:00 2001
From: Harshdeep Singh <6162866+harsh62@users.noreply.github.com>
Date: Mon, 13 May 2024 19:18:59 -0400
Subject: [PATCH 9/9] fixing the mdx link
---
.../switching-authentication-flows/index.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
index 6be3bce761c..6d7f829154f 100644
--- a/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
+++ b/src/pages/[platform]/build-a-backend/auth/connect-your-frontend/switching-authentication-flows/index.mdx
@@ -93,7 +93,7 @@ backend.auth.resources.cfnResources.cfnUserPoolClient.explicitAuthFlows = [
Amazon Cognito provides a trigger to migrate users from your existing user directory seamlessly into Cognito. You achieve this by configuring your User Pool's "Migration" trigger which invokes a Lambda function whenever a user that does not already exist in the user pool authenticates, or resets their password.
-In short, the Lambda function will validate the user credentials against your existing user directory and return a response object containing the user attributes and status on success. An error message will be returned if an error occurs. There's documentation around [how to set up this migration flow](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-import-using-lambda.html) and more detailed instructions on [how the lambda should handle request and response objects]((https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html#cognito-user-pools-lambda-trigger-syntax-user-migration)).
+In short, the Lambda function will validate the user credentials against your existing user directory and return a response object containing the user attributes and status on success. An error message will be returned if an error occurs. There's documentation around [how to set up this migration flow](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-import-using-lambda.html) and more detailed instructions on [how the lambda should handle request and response objects](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html#cognito-user-pools-lambda-trigger-syntax-user-migration).
## CUSTOM_AUTH flow