Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/fragments/lib/auth/common/device_features/common.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import android1 from "/src/fragments/lib/auth/android/device_features/10_remembe

import js2 from "/src/fragments/lib/auth/js/device_features/10_rememberDevice.mdx";

<Fragments fragments={{js: js2}} />
<Fragments fragments={{js: js2, 'react-native': js2}} />

import flutter3 from "/src/fragments/lib/auth/flutter/device_features/10_rememberDevice.mdx";

Expand All @@ -63,7 +63,7 @@ import android5 from "/src/fragments/lib/auth/android/device_features/20_forgetD

import js6 from "/src/fragments/lib/auth/js/device_features/20_forgetDevice.mdx";

<Fragments fragments={{js: js6}} />
<Fragments fragments={{js: js6, 'react-native': js6}} />

import flutter7 from "/src/fragments/lib/auth/flutter/device_features/20_forgetDevice.mdx";

Expand All @@ -82,7 +82,7 @@ import android9 from "/src/fragments/lib/auth/android/device_features/30_fetchDe

import js10 from "/src/fragments/lib/auth/js/device_features/30_fetchDevice.mdx";

<Fragments fragments={{js: js10}} />
<Fragments fragments={{js: js10, 'react-native': js10}} />

import flutter11 from "/src/fragments/lib/auth/flutter/device_features/30_fetchDevice.mdx";

Expand All @@ -96,4 +96,4 @@ import flutter11 from "/src/fragments/lib/auth/flutter/device_features/30_fetchD
* **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 not opt-ed in to having the device remembered. This use case is used 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 a device, you can use the `Amplify.Auth.forgetDevice()` API to remove this device from being both remembered and tracked.
* In the event that you no longer want to remember or track a device, you can use the `Auth.forgetDevice()` API to remove this device from being both remembered and tracked.
54 changes: 27 additions & 27 deletions src/fragments/lib/auth/js/emailpassword.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,20 @@ The `Auth.signUp` promise returns a data object of type [`ISignUpResult`](https:
}
```

### Auto sign in after sign up

If you enabled `autoSignIn`, the `sign up` function will dispatch `autoSignIn` hub event after successful confirmation.
If authentication was successful, the event will contain `CognitoUser` in data object. If auto sign in failed, it will dispatch `autoSignIn_failure` event.
### Re-send sign up confirmation code

If user didn't get a confirmation code, you can use `resendSignUp` function to send a new one.
```js
import { Hub } from 'aws-amplify';
import { Auth } from 'aws-amplify';

function listenToAutoSignInEvent() {
Hub.listen('auth', ({ payload }) => {
const { event } = payload;
if (event === 'autoSignIn') {
const user = payload.data;
// assign user
} else if (event === 'autoSignIn_failure') {
// redirect to sign in page
}
})
async function resendConfirmationCode() {
try {
await Auth.resendSignUp(username);
console.log('code resent successfully');
} catch (err) {
console.log('error resending code: ', err);
}
}

```

### Confirm sign up
Expand All @@ -74,20 +68,26 @@ async function confirmSignUp() {
}
```

### Re-send sign up confirmation code
### Auto sign in after sign up

If you enabled `autoSignIn`, the `sign up` function will dispatch `autoSignIn` hub event after successful confirmation.
If authentication was successful, the event will contain `CognitoUser` in data object. If auto sign in failed, it will dispatch `autoSignIn_failure` event.

If user didn't get a confirmation code, you can use `resendSignUp` function to send a new one.
```js
import { Auth } from 'aws-amplify';
import { Hub } from 'aws-amplify';

async function resendConfirmationCode() {
try {
await Auth.resendSignUp(username);
console.log('code resent successfully');
} catch (err) {
console.log('error resending code: ', err);
}
function listenToAutoSignInEvent() {
Hub.listen('auth', ({ payload }) => {
const { event } = payload;
if (event === 'autoSignIn') {
const user = payload.data;
// assign user
} else if (event === 'autoSignIn_failure') {
// redirect to sign in page
}
})
}

```

### Custom Attributes
Expand All @@ -105,7 +105,7 @@ Auth.signUp({
})
```

> Amazon Cognito does not dynamically create custom attributes on sign up. In order to use a custom attribute, the attribute must be first created in the user pool. To open the User Pool to create custom attributes using the Amplify ClI, run `amplify console auth`. If you are not using the Amplify CLI, you can view the user pool by visiting the AWS console and opening the Amazon Cognito dashboard.
> Amazon Cognito does not dynamically create custom attributes on sign up. In order to use a custom attribute, the attribute must be first [created in the user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html). To open the User Pool to create custom attributes using the Amplify ClI, run `amplify console auth`. If you are not using the Amplify CLI, you can view the user pool by visiting the AWS console and opening the Amazon Cognito dashboard.

## Sign-in

Expand Down
32 changes: 0 additions & 32 deletions src/fragments/lib/auth/js/mfa.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,38 +82,6 @@ Auth.getPreferredMFA(user, {
});
```

## Allow users to select MFA type

When working with multiple MFA Types, you can let the app user select the desired authentication method. `SelectMFAType` UI Component, which is provided with `aws-amplify-react` package, renders a list of available MFA types.

```javascript
import { Amplify } from 'aws-amplify';
import awsconfig from './aws-exports';
import { SelectMFAType } from 'aws-amplify-react';

Amplify.configure(awsconfig);

// Please have at least TWO types
// Please make sure you set it properly according to your Cognito User pool
const MFATypes = {
SMS: true, // if SMS enabled in your user pool
TOTP: true, // if TOTP enabled in your user pool
Optional: true, // if MFA is set to optional in your user pool
}

class App extends Component {
// ...
render() {
return (
// ...
<SelectMFAType authData={this.props.authData} MFATypes={MFATypes}>
)
}
}

export default withAuthenticator(App, true);
```

## Advanced use cases

### Sign-in with custom auth challenges
Expand Down
184 changes: 184 additions & 0 deletions src/fragments/lib/auth/js/react-native-mfa.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
<Callout>
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/).
</Callout>

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. AWS Amplify uses Amazon Cognito to provide MFA. Please see [Amazon Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html) for more information about setting up MFA in Amazon Cognito.

Once you enable MFA on Amazon Cognito, you can configure your app to work with MFA.

## Setup TOTP

With TOTP (Time-based One-time Password), your app user is challenged to complete authentication using a time-based one-time (TOTP) password after their username and password have been verified.

You can setup TOTP for a user in your app:

```javascript
import { Auth } from 'aws-amplify';

// To setup TOTP, first you need to get a `authorization code` from Amazon Cognito
// `user` is the current Authenticated user
Auth.setupTOTP(user).then((code) => {
// display setup code to user which can be used to manually add an account to Authenticator apps
});

// ...

// Then you will have your TOTP account in your TOTP-generating app (like Google Authenticator)
// Use the generated one-time password to verify the setup
Auth.verifyTotpToken(user, challengeAnswer)
.then(() => {
// don't forget to set TOTP as the preferred MFA method
Auth.setPreferredMFA(user, 'TOTP');
// ...
})
.catch((e) => {
// Token is not verified
});
```

## Setup MFA type

Multiple MFA types supported by Amazon Cognito. You can set the preferred method in your code:

```javascript
import { Auth } from 'aws-amplify';

// You can select preferred mfa type, for example:
// Select TOTP as preferred
Auth.setPreferredMFA(user, 'TOTP')
.then((data) => {
console.log(data);
// ...
})
.catch((e) => {});

// Select SMS as preferred
Auth.setPreferredMFA(user, 'SMS');

// Select no-mfa
Auth.setPreferredMFA(user, 'NOMFA');
```

## Retrieve current preferred MFA type

You can get current preferred MFA type in your code:

```javascript
import { Auth } from 'aws-amplify';

// Will retrieve the current mfa type from cache
Auth.getPreferredMFA(user, {
// Optional, by default is false.
// If set to true, it will get the MFA type from server side instead of from local cache.
bypassCache: false
}).then((data) => {
console.log('Current preferred MFA type is: ' + data);
});
```

## Advanced use cases

### Sign-in with custom auth challenges

When signing in with user name and password, you will either sign in directly or be asked to pass some challenges before getting 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 those two parameters.

ChallengeName:

- `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(the one time password) which requires the user to go through some steps to generate those passwords. You can start the setup process by `Auth.setupTOTP`.

The following code is only for demonstration purpose:

```javascript
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 = 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 } = 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
Auth.setupTOTP(user);
} 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);
}
}
}
```

### Sign-in with custom validation data for Lambda Trigger

You can also pass an object which has the username, password and validationData which is sent to a PreAuthentication Lambda trigger

```js
try {
const user = await Auth.signIn({
username, // Required, the username
password, // Optional, the password
validationData // Optional, an arbitrary key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda trigger as-is. It can be used to implement additional validations around authentication
});
console.log('user is signed in!', user);
} catch (error) {
console.log('error signing in:', error);
}
```

### Forcing Email Uniqueness in Cognito User Pools

When your Cognito User Pool sign-in options are set to "_Username_", and "_Also allow sign in with verified email address_", the _signUp()_ method creates a new user account every time it's called, without validating email uniqueness. In this case you will end up having multiple user pool identities and all previously created accounts will have their _email_verified_ attribute changed to _false_.

To enforce Cognito User Pool signups with a unique email, you need to change your User Pool's _Attributes_ setting in [Amazon Cognito console](https://console.aws.amazon.com/cognito) as the following:

![cup](/images/cognito_user_pool_settings.png)
Loading