aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.42k stars 2.12k forks source link

Having problems when signing in using withAuthenticator and problems using { Auth } from 'aws-amplify' when not - why is this? #13243

Closed marcuscapacity closed 5 months ago

marcuscapacity commented 5 months ago

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

Amplify CLI

Environment information

``` # Put output below this line System: OS: macOS 14.3 CPU: (10) arm64 Apple M2 Pro Memory: 6.53 GB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 20.11.1 - ~/.nvm/versions/node/v20.11.1/bin/node Yarn: 1.22.21 - ~/.nvm/versions/node/v20.11.1/bin/yarn npm: 10.5.2 - ~/.nvm/versions/node/v20.11.1/bin/npm Browsers: Chrome: 123.0.6312.123 Edge: 123.0.2420.81 Safari: 17.3 npmPackages: @aws-amplify/react-native: ^1.0.28 => 1.0.28 @aws-amplify/ui-react-native: ^2.1.5 => 2.1.5 @babel/core: ^7.20.0 => 7.24.4 @react-native-async-storage/async-storage: 1.21.0 => 1.21.0 @react-native-community/netinfo: 11.1.0 => 11.1.0 HelloWorld: 0.0.1 amazon-cognito-identity-js: ^6.3.12 => 6.3.12 amazon-cognito-identity-js/internals: undefined () aws-amplify: ^6.0.28 => 6.0.28 aws-amplify/adapter-core: undefined () aws-amplify/analytics: undefined () aws-amplify/analytics/kinesis: undefined () aws-amplify/analytics/kinesis-firehose: undefined () aws-amplify/analytics/personalize: undefined () aws-amplify/analytics/pinpoint: undefined () aws-amplify/api: undefined () aws-amplify/api/server: undefined () aws-amplify/auth: undefined () aws-amplify/auth/cognito: undefined () aws-amplify/auth/cognito/server: undefined () aws-amplify/auth/enable-oauth-listener: undefined () aws-amplify/auth/server: undefined () aws-amplify/data: undefined () aws-amplify/data/server: undefined () aws-amplify/datastore: undefined () aws-amplify/in-app-messaging: undefined () aws-amplify/in-app-messaging/pinpoint: undefined () aws-amplify/push-notifications: undefined () aws-amplify/push-notifications/pinpoint: undefined () aws-amplify/storage: undefined () aws-amplify/storage/s3: undefined () aws-amplify/storage/s3/server: undefined () aws-amplify/storage/server: undefined () aws-amplify/utils: undefined () expo: ~50.0.14 => 50.0.15 expo-status-bar: ~1.11.1 => 1.11.1 react: 18.2.0 => 18.2.0 react-native: 0.73.6 => 0.73.6 react-native-get-random-values: ~1.8.0 => 1.8.0 react-native-safe-area-context: 4.8.2 => 4.8.2 react-native-url-polyfill: ^2.0.0 => 2.0.0 npmGlobalPackages: @aws-amplify/cli: 12.10.3 aws-cdk: 2.130.0 corepack: 0.23.0 expo-cli: 6.3.10 npm: 10.5.2 react-native-cli: 2.0.1 ts-node: 10.9.2 typescript: 5.4.3 yarn: 1.22.21 ```

Describe the bug

{ Auth } is not correctly being read as an import from 'aws-amplify'. There are four files 'aws-amplify' stems from:

Not sure if that in itself is incorrect?

Because of this, Auth.signIn(username, password); is not working. Although the IDE does not have an error when using the .signIn and .signUp methods, right clicking them takes you to their appropriate files:

export const MACHINE_PROP_KEYS: Record<
  AuthenticatorRouteComponentKey,
  AuthenticatorMachineContextKey[]
> = {
  confirmResetPassword: CONFIRM_RESET_PASSWORD_MACHINE_KEYS,
  confirmSignIn: CONFIRM_SIGN_IN_MACHINE_KEYS,
  confirmSignUp: CONFIRM_SIGN_UP_MACHINE_KEYS,
  confirmVerifyUser: CONFIRM_VERIFY_USER_MACHINE_KEYS,
  forceNewPassword: FORCE_NEW_PASSWORD_MACHINE_KEYS,
  signIn: SIGN_IN_MACHINE_KEYS,
  signUp: SIGN_UP_MACHINE_KEYS,
  forgotPassword: RESET_PASSWORD_MACHINE_KEYS,
  setupTotp: SETUP_TOTP_MACHINE_KEYS,
  verifyUser: VERIFY_USER_MACHINE_KEYS,
};

This leads to the error message being caught in this try/catch block:

async function signIn() {
    try {
      await Auth.signIn(username, password);
      console.log('Sign-in successful');
      Alert.alert('Sign-in Successful', 'You have successfully signed in.');
    } catch (error) {
      console.error('Error signing in:', error);
      Alert.alert('Error', 'An error occurred while signing in. Please check your credentials and try again.');
    }
  }

Expected behavior

The user, who I have managed to signUp with as shown by the user Pool in Cognito showing my user's email address, should be able to sign in.

Reproduction steps

I have followed all the steps here: https://blog.logrocket.com/aws-amplify-react-native-tutorial-examples/ But since withAuthenticator had a problem when trying to sign in but did not show any useful error messages, I have converted my code to use the auth methods directly (see code snippet below)

Code Snippet

// Put your code below this line.
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import { Amplify } from 'aws-amplify';
import awsExports from './src/aws-exports';
Amplify.configure(awsExports)
import { Auth } from 'aws-amplify';
export default function AuthScreen() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  async function signUp() {
    try {
      await Auth.signUp({
        username,
        password,
        // You can include additional attributes here
      });
      console.log('Sign-up successful');
      Alert.alert('Sign-up Successful', 'Please check your email to verify your account.');
    } catch (error) {
      console.error('Error signing up:', error);
      Alert.alert('Error', 'An error occurred while signing up. Please try again later.');
    }
  }

  async function signIn() {
    try {
      await Auth.signIn(username, password);
      console.log('Sign-in successful');
      Alert.alert('Sign-in Successful', 'You have successfully signed in.');
    } catch (error) {
      console.error('Error signing in:', error);
      Alert.alert('Error', 'An error occurred while signing in. Please check your credentials and try again.');
    }
  }

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <TextInput
        placeholder="Username"
        onChangeText={(text) => setUsername(text)}
        value={username}
        style={{ marginBottom: 10, padding: 10, borderColor: 'gray', borderWidth: 1, borderRadius: 5, width: 300 }}
      />
      <TextInput
        placeholder="Password"
        onChangeText={(text) => setPassword(text)}
        value={password}
        secureTextEntry
        style={{ marginBottom: 10, padding: 10, borderColor: 'gray', borderWidth: 1, borderRadius: 5, width: 300 }}
      />
      <Button title="Sign Up" onPress={signUp} />
      <Button title="Sign In" onPress={signIn} />
    </View>
  );
}

Log output

``` // Put your logs below this line ```

aws-exports.js

/* eslint-disable */
// WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = {
    "aws_project_region": "eu-west-2",
    "aws_cognito_identity_pool_id": "eu-west-2:132fbb95-9dce-4662-8462-b1e3929d898f",
    "aws_cognito_region": "eu-west-2",
    "aws_user_pools_id": "eu-west-2_X8B9fXjmx",
    "aws_user_pools_web_client_id": "385ctof107h5g007lf3d68oq2e",
    "oauth": {},
    "aws_cognito_username_attributes": [
        "EMAIL"
    ],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": []
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

export default awsmobile;

Manual configuration

{
  "aws_project_region": "eu-west-2",
  "aws_cognito_identity_pool_id": "eu-west-2:132fbb95-9dce-4662-8462-b1e3929d898f",
  "aws_cognito_region": "eu-west-2",
  "aws_user_pools_id": "eu-west-2_X8B9fXjmx",
  "aws_user_pools_web_client_id": "385ctof107h5g007lf3d68oq2e",
  "oauth": {},
  "aws_cognito_username_attributes": [
    "EMAIL"
  ],
  "aws_cognito_social_providers": [],
  "aws_cognito_signup_attributes": [
    "EMAIL"
  ],
  "aws_cognito_mfa_configuration": "OFF",
  "aws_cognito_mfa_types": [
    "SMS"
  ],
  "aws_cognito_password_protection_settings": {
    "passwordPolicyMinLength": 8,
    "passwordPolicyCharacters": []
  },
  "aws_cognito_verification_mechanisms": [
    "EMAIL"
  ]
}

Additional configuration

{
    "UserPool": {
        "Id": "eu-west-2_X8B9fXjmx",
        "Name": "awsamplifyauthenticadab1a625_userpool_dab1a625-dev",
        "Policies": {
            "PasswordPolicy": {
                "MinimumLength": 8,
                "RequireUppercase": false,
                "RequireLowercase": false,
                "RequireNumbers": false,
                "RequireSymbols": false,
                "TemporaryPasswordValidityDays": 7
            }
        },
        "DeletionProtection": "INACTIVE",
        "LambdaConfig": {},
        "LastModifiedDate": "2024-04-11T22:49:17.170000+01:00",
        "CreationDate": "2024-04-10T23:05:41.991000+01:00",
        "SchemaAttributes": [
            {
                "Name": "profile",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "address",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "birthdate",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "10",
                    "MaxLength": "10"
                }
            },
            {
                "Name": "gender",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "preferred_username",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "updated_at",
                "AttributeDataType": "Number",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "NumberAttributeConstraints": {
                    "MinValue": "0"
                }
            },
            {
                "Name": "website",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "picture",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "identities",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {}
            },
            {
                "Name": "sub",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": false,
                "Required": true,
                "StringAttributeConstraints": {
                    "MinLength": "1",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "phone_number",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "phone_number_verified",
                "AttributeDataType": "Boolean",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false
            },
            {
                "Name": "zoneinfo",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "locale",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "email",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": true,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "email_verified",
                "AttributeDataType": "Boolean",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false
            },
            {
                "Name": "given_name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "family_name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "middle_name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "nickname",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            }
        ],
        "AutoVerifiedAttributes": [
            "email"
        ],
        "UsernameAttributes": [
            "email"
        ],
        "EmailVerificationMessage": "Your verification code is {####}",
        "EmailVerificationSubject": "Your verification code",
        "VerificationMessageTemplate": {
            "EmailMessage": "Your verification code is {####}",
            "EmailSubject": "Your verification code",
            "DefaultEmailOption": "CONFIRM_WITH_CODE"
        },
        "UserAttributeUpdateSettings": {
            "AttributesRequireVerificationBeforeUpdate": [
                "email"
            ]
        },
        "MfaConfiguration": "OFF",
        "EstimatedNumberOfUsers": 1,
        "EmailConfiguration": {
            "EmailSendingAccount": "COGNITO_DEFAULT"
        },
        "UserPoolTags": {},
        "AdminCreateUserConfig": {
            "AllowAdminCreateUserOnly": false,
            "UnusedAccountValidityDays": 7
        },
        "UsernameConfiguration": {
            "CaseSensitive": false
        },
        "Arn": "arn:aws:cognito-idp:eu-west-2:851725470299:userpool/eu-west-2_X8B9fXjmx",
        "AccountRecoverySetting": {
            "RecoveryMechanisms": [
                {
                    "Priority": 1,
                    "Name": "verified_email"
                },
                {
                    "Priority": 2,
                    "Name": "verified_phone_number"
                }
            ]
        }
    }
}

Mobile Device

No response

Mobile Operating System

android

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

jimblanc commented 5 months ago

@marcuscapacity Thank you for your report. Your example code appears to be using Amplify v5 APIs, while you have a dependency on Amplify v6 (which introduced functional APIs across the library). I'd recommend taking a look at our official v6 Auth documentation: https://docs.amplify.aws/react/build-a-backend/auth/enable-sign-up/

Additionally, looking at your dependencies you should be able to remove amazon-cognito-identity-js, which is no longer required for v6.

cwomack commented 5 months ago

Closing this issue as we have not heard back from you. If you are still experiencing this, please feel free to reply back and provide any information previously requested and we'd be happy to re-open the issue.

Thank you!