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.44k stars 2.13k forks source link

Mobile SignIn function failure from @aws-amplify/auth but WebVersion works (using Expo) #13964

Open ajaviles13 opened 3 weeks ago

ajaviles13 commented 3 weeks 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.4 CPU: (14) arm64 Apple M3 Max Memory: 2.73 GB / 36.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 22.9.0 - /opt/homebrew/bin/node npm: 10.9.0 - /opt/homebrew/bin/npm Browsers: Chrome: 130.0.6723.70 Safari: 17.4 npmPackages: @aws-amplify/api: ^6.0.54 => 6.0.55 @aws-amplify/api/internals: undefined () @aws-amplify/api/server: undefined () @aws-amplify/auth: ^6.5.0 => 6.5.0 (6.5.3) @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/core: ^6.4.5 => 6.4.6 @aws-amplify/core/internals/adapter-core: undefined () @aws-amplify/core/internals/aws-client-utils: undefined () @aws-amplify/core/internals/aws-client-utils/composers: undefined () @aws-amplify/core/internals/aws-clients/cognitoIdentity: undefined () @aws-amplify/core/internals/aws-clients/pinpoint: undefined () @aws-amplify/core/internals/providers/pinpoint: undefined () @aws-amplify/core/internals/utils: undefined () @aws-amplify/core/server: undefined () @aws-amplify/react-native: ^1.1.6 => 1.1.6 @aws-amplify/ui-react-native: ^2.2.16 => 2.2.16 @babel/core: ^7.20.0 => 7.25.8 @react-native-async-storage/async-storage: ^2.0.0 => 2.0.0 @react-native-community/masked-view: ^0.1.11 => 0.1.11 @react-native-community/netinfo: ^11.4.1 => 11.4.1 @react-native-picker/picker: ^2.8.1 => 2.8.1 @react-navigation/native: ^6.1.18 => 6.1.18 HelloWorld: 0.0.1 aws-amplify: ^6.6.6 => 6.6.6 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 () axios: ^1.7.7 => 1.7.7 expo: ~51.0.38 => 51.0.38 expo-constants: ~16.0.1 => 16.0.2 expo-font: ^12.0.10 => 12.0.10 expo-linking: ~6.3.1 => 6.3.1 expo-router: ~3.5.9 => 3.5.23 expo-splash-screen: ~0.27.4 => 0.27.6 (0.27.5) expo-status-bar: ~1.12.1 => 1.12.1 nativewind: ^2.0.11 => 2.0.11 react: 18.2.0 => 18.2.0 react-dom: 18.2.0 => 18.2.0 react-native: 0.74.5 => 0.74.5 (0.73.10) react-native-appwrite: ^0.5.0 => 0.5.0 react-native-dotenv: ^3.4.11 => 3.4.11 react-native-dropdown-select-list: ^2.0.5 => 2.0.5 react-native-gesture-handler: ~2.16.1 => 2.16.2 react-native-get-random-values: ^1.11.0 => 1.11.0 react-native-picker-select: ^9.3.1 => 9.3.1 react-native-reanimated: ~3.10.1 => 3.10.1 react-native-safe-area-context: ^4.11.1 => 4.11.1 react-native-screens: 3.31.1 => 3.31.1 react-native-url-polyfill: ^2.0.0 => 2.0.0 react-native-web: ~0.19.6 => 0.19.12 tailwindcss: ^3.3.2 => 3.3.2 npmGlobalPackages: @aws-amplify/cli: 12.13.0 npm: 10.9.0 ```

Describe the bug

I am integrating all the "aws-amplify/auth" functions into my custom UI. I've already successfully integrated the {signUp, signOut, confirmSignUp, resendSignUp } functions and they work great. No errors and my account I create (using email as username) goes right into my Cognito Pool smoothly which was set up through AWS Amplify Studio. Logout button works great when I get to my "Home" screen after Signing Up and Confirming my 6-digit Code. This is the return value I get by overlaying my 'confirmSignUp' and 'signUp' responses and storing them in a global app variable called "user": 'newSetUser': {"isSignUpComplete": true, "nextStep": {"codeDeliveryDetails": {"attributeName": "email", "deliveryMedium": "EMAIL", "destination": "a@g"}, "signUpStep": "DONE"}, "userId": "c14b75c0-70b1-7048-9c0b-07ba8df12052"}

The problem is after I log out... I try to Sign In using my custom Sign In UI screen that is connected to the {signIn} function from "aws-amplify/auth". When clicking "Sign In", I get this bizarre error that I cannot figure out what is going on. I can clearly see my username (email) and password get passed into the 'signIn' function correctly and they are the same creds I used upon set up (I've validated this over and over again). This is the error message: "Error during sign in: [Unknown: An unknown error has occurred.]"

Expected behavior

For me to simply sign in with the correct credentials with no errors. I've watched and followed several YouTube videos and thread approaches to this simply "signIn" function within "aws-amplify/auth" but I always come back to get this unknown error message...

Reproduction steps

  1. I go to my Sign In Screen (after logging out of a verified account)
  2. Enter in credentials (email + password) I just used for creating my account (but logged out once I entered the app's protected path)
  3. Click "Sign In"
  4. The TextInputs (email and password) are passed correctly via props into my custom "aws_signIn" function which is show below in the Code Snippet

Code Snippet

// Put your code below this line.
`import { Auth, API, Storage, Amplify } from 'aws-amplify';
import config from '../src/aws-exports'; // Ensure this path points to your aws-exports.js file
import { signIn, signUp, autoSignIn, signOut, confirmSignUp, resendSignUp } from 'aws-amplify/auth';

// Enable detailed logging for AWS Amplify
Amplify.configure(config); // Correctly configure Amplify with the config file

// ========================== //
// === User Authentication == //
// ========================== //

// Sign in a user
export const aws_signIn = async ({ email, password }) => {

    try {
        console.log("'Amplify.js' Email: ", email.trim().toLowerCase());
        console.log("'Amplify.js' Password: ", password.trim());

        let clean_email = email.trim().toLowerCase();
        let clean_password = password.trim();

        const signInResult = await signIn({
            'username': clean_email,
            'password': clean_password
        });

        console.log('signInResult: ', signInResult);

        return signInResult;
    } catch (e) {
        console.error('Error during sign in:', e); // Log the entire error object
        throw new Error(e.message || 'An unknown error occurred during sign in.');
    }
};`

**====== The code that is executed once the "Sign Up" button is clicked below ======**
`import { aws_signIn } from '../../lib/amplify'
import { useGlobalContext } from "../../context/GlobalProvider"; 

const SignIn = () => {
  const { setUser, setIsLoggedIn } = useGlobalContext();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  let onlyShowOneAlert = false;

  const [form, setForm] = useState({
    email: '',
    password: ''
  });

  const onSignInPressed = async () => {
    setError('');

    if(!form.email || !form.password) {
      Alert.alert('Sign In Error', 'Email & Password required to sign in.');
      onlyShowOneAlert = true;
    }
    setIsSubmitting(true);
    try {  
      const signInResult = await aws_signIn(form);
      setUser(signInResult);
      setIsLoggedIn(true);
      router.replace('/home');  // Redirect the user to the home page
    } catch (err) {
        setError(err.message)
        console.log('Catch Error: ', error);
    } finally{
        setIsSubmitting(false);
        console.log('Finally Error: ', error);
    }
  };`

**### TERMINAL LOG UPON PASSING IN TextInput Props:**
LOG: 'Amplify.js' Email:  a************@gmail.com
LOG: 'Amplify.js' Password:  TestPassword123
 ERROR  Error during sign in: [Unknown: An unknown error has occurred.]
 LOG  Catch Error:  An unknown error has occurred.
 LOG  Finally Error:  An unknown error has occurred.

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": "us-east-2", "aws_cognito_identity_pool_id": "us-east-2:#########-####-####-####-###########", "aws_cognito_region": "us-east-2", "aws_user_poolsid": "us-east-2##########", "aws_user_pools_web_client_id": "#########################", "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": 6, "passwordPolicyCharacters": [] }, "aws_cognito_verification_mechanisms": [ "EMAIL" ] };

export default awsmobile;

Manual configuration

No response

Additional configuration

No response

Mobile Device

iPhone 15 Pro

Mobile Operating System

iOS18.0.1

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

Using Expo

cwomack commented 3 weeks ago

Hello, @ajaviles13 and thanks for opening this issue. Given that there's no information in the error message to help us here, we might need to get some additional info from the network requests when this error happens. Can you share a screenshot or the details of what your responses are from Cognito when this happens? Here's a link to the RN docs to help with the network logging.

We know that getting the logs is tough sometimes in React Native, so if you're open to sharing a minimal sample app that reproduces this reliably then that would be great as well.

cwomack commented 3 weeks ago

@ajaviles13, have one more request after digging into your dependencies. It looks like you've got the following outdated dependencies:

    @aws-amplify/core: ^6.4.5 => 6.4.6 
    @aws-amplify/auth: ^6.5.0 => 6.5.0 (6.5.3)

Can you see if removing these and only having the aws-amplify: ^6.6.6 => 6.6.6 resolves the issue?

ajaviles13 commented 3 weeks ago

Hi @cwomack, thanks for getting back to me. I tried the following:

  1. Updated both "@aws-amplify/core"=>6.4.6 and "@aws-amplify/auth" => 6.5.0 but that did not do anything. Same exact Sign In is failing with the same unknown error
  2. I removed both "@aws-amplify/core" and "@aws-amplify/auth" from my dependencies and ensured my "aws-amplify": "^6.6.6". I tried performing a login and still getting the same [Unknown: An unknown error has occurred.]

I am happy to share my React Native project folder. I filled in any account sensitive info with "#" plus this is an MVP app where I am seeing if I will be using AWS Auth for Authentication.

What is the best way for me to provide you with a zip file of my App Project Folder?

I'll also provide more information on the general folder structure of my app as well.

cwomack commented 2 weeks ago

@ajaviles13, best way to share it (if you're open to it) would be to make the repo public if you remove any sensitive information that might be on it, invite me to the private repo if you'd like, or hop on our AWS Amplify Discord server and you we can follow up there as well with a DM.

ajaviles13 commented 2 weeks ago

@cwomack - great. I removed sensitive information and shared everything but my "node_modules" folder in a public repo here: [aws-auth-error](https://github.com/ajaviles13/aws-auth-error/tree/main). Take a look at the README file before diving in.

This isn't a time sensitive matter because I have a functional workaround using Appwrite for my Auth workflow and webhooks to sync new users/data created upon sign up directly into my AWS infrastructure. But I would love to have my Auth workflow within AWS.

ajaviles13 commented 2 weeks ago

@cwomack - I wonder if it has something to do with CORS. I am not an expert at CORS but watched a couple videos and may be thinking it is correlated with my AWS Auth workflow failing to auto sign in and sign in as well.

Edited: Never mind, CORS only affects web browsing and not Mobile Apps

cwomack commented 2 weeks ago

@ajaviles13, thank you for the sample repo!

Few more questions to better understand the architecture here as I haven't used Appwrite personally and am just digging into their docs. Are you only trying to incorporate the Auth category then from Amplify via one of the "Auth Journeys" mentioned by Appwrite?

Additionally, I see you're wrapping your Auth API's and using autoSignIn(). This may cause issues because of how autoSignIn() behaves when wrapped, more on that here. Can you see if refactoring to use the Auth API's directly resolves the issue or gives you any different errors?

ajaviles13 commented 2 weeks ago

Hi @cwomack, thanks for the reply. Let's forget I even mentioned Appwrite, all that implementation was stripped out of the repo that I uploaded earlier. Goal here is to get AWS Amplify Auth working as expected.

After attempting the "wrapping Auth API" suggestion you made I am still getting these issues (I also added a Loom Recording below):

  1. Error Message when signing up and using the same code as V6 AWS Documentation says. It stems from the code below " // 3. Trigger autoSignIn event - will not be triggered automatically".
  2. Error when signing in after I have confirmed and authenticated my account. This error message is returned "Error during sign in: [Unknown: An unknown error has occurred.]"
  3. Error code when trying to refresh app and autoSignIn: "[NotAuthorizedException: Unauthenticated access is not supported for this identity pool.]"

Please see this Loom recording of the issues I am facing: https://www.loom.com/share/b50554ecf672462596332686ea29c93b?sid=69cdcde5-7203-4f56-b31a-ec0f5e2e4e6e

I also updated the "amplify.js", "confirmCodeUponSignUp.jsx", and "signUp.jsx" in aws-auth-error based on the V6 documentation which is still leading me to the errors defined above.

Let me know if there is anything else I can provide that will be helpful.

ashika112 commented 2 weeks ago

@ajaviles13 Thanks for the very detailed video and explaining through your workflow. Really appreciate this. Looking at the code in the video i noticed couple of things and gonna try and help based on the observation there.

  1. From the looks of it, your autoSignIn code looks good to me, could you provide me with the result for signUp nextStep for me?

  2. [NotAuthorizedException: Unauthenticated access is not supported for this identity pool.] - This is probably coming from API call before signing In. If guest access is not allowed per your backend setup, then API call for other parts of Amplify (in this case, getCurrentUser will throw this error. Because you can not get current User if you are not logged in based on your backend setup.

Meanwhile, we will work on reproducing the error in a fresh RN app to see if we can isolated it to some setup.

ashika112 commented 2 weeks ago

Also could you confirm if you have followed this getting started guide? Or added all the dependencies mentioned here for your RN app with exception of @aws-amplify/ui-react-native if you are not using that?

ajaviles13 commented 2 weeks ago

Hi @ashika112. Thanks for jumping in here. To answer you questions:

  1. Here are the console logs for "isSignUpComplete", "userId", and "nextStep" when running: const {isSignUpComplete, userId, nextStep} = await signUp({... the rest my handleSignUp() code}) LOG isSignUpComplete: false LOG userId: 618b3560-9081-7012-1a36-88a9f18648d1 LOG nextStep: {"codeDeliveryDetails": {"attributeName": "email", "deliveryMedium": "EMAIL", "destination": "a@g"}, "signUpStep": "CONFIRM_SIGN_UP"}

    1. That is correct, "[NotAuthorizedException: Unauthenticated access is not supported for this identity pool.]" should display if a user hasn't signed up yet. But if the user signs up successfully then they should remain logged in even after refreshing the app. That "NotAuthorizedException" message displays every time I refresh the app even when I signed up successfully. A user will not be able to access the app's features if they haven't created an account successfully, as there is no guest access allowed.

    2. Yes, I reviewed that and installed all those dependencies. "ui-react-native" does not apply to my case because I am not using the {Authenticator, useAuthenticator} from "@aws-amplify/ui-react-native" because I have my own Sign Up and Sign In UI. This is why I referenced Migrate from v5 to v6 to implement my auth functions. Is this the correct approach ?

ashika112 commented 2 weeks ago

Hi @ajaviles13 I can confirm autoSignIn works as expected in react native. I created a fresh sample app with signup, confirmsignup, autosignIn and everything works as expected. My doubt would the way in which the code is called and executed might be what is causing u the issue. It might some race condition happening in your code base.

Screenshot 2024-11-06 at 1 01 21 PM
ashika112 commented 2 weeks ago

my code is as simple as,

import {
  autoSignIn,
  confirmSignUp,
  deleteUser,
  getCurrentUser,
  signUp,
} from "aws-amplify/auth";
import { Button, StyleSheet, Text, TextInput, View } from "react-native";
import { useState } from "react";

import outputs from "./amplify_outputs.json";
import { Amplify } from "aws-amplify";

Amplify.configure(outputs);

const SignUpButton = () => {
  return (
    <View>
      <Button
        title="Sign Up"
        onPress={async () => {
          const result = await signUp({
            username: "...",
            password: "....",
            options: { userAttributes: {}, autoSignIn: true },
          });
        }}
      />
    </View>
  );
};

const ConfirmButton = () => {
  const [text, onChangeText] = useState("");

  return (
    <View>
      <TextInput onChangeText={onChangeText} value={text} placeholder="code" />
      <Button
        title="Confirm Sign Up"
        onPress={async () => {
          const result = await confirmSignUp({
            username: "...",
            confirmationCode: text,
          });
          console.log(result);
          if (result.nextStep.signUpStep === "COMPLETE_AUTO_SIGN_IN") {
            const res = await autoSignIn();
            console.log("autoSignIn", res);
            console.log("currentUser", await getCurrentUser());
          }
        }}
      />
    </View>
  );
};

const DeleteUserButton = () => {
  return (
    <View>
      <Button
        title="Delete User"
        onPress={async () => {
          const result = await deleteUser();
          console.log("delete user", result);
        }}
      />
    </View>
  );
};

export default function App() {
  const [step, setStep] = useState();
  const [code, setCode] = useState();
  return (
    <View style={styles.container}>
      <SignUpButton />
      <ConfirmButton />
      <DeleteUserButton />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});
ajaviles13 commented 2 weeks ago

@ashika112 - thank you for sharing your findings and glad to hear you got it working. I am performing a deeper analysis on my code base. I've been able to implement both Appwrite and Supabase Auth (used in different app files but same code base) perfectly with the same unplug/plugin approach in my code base. I'll need to dig deeper why my codebase isn't working with AWS Auth. Thanks again

cwomack commented 1 week ago

@ajaviles13, wanted to circle back and see if you had a chance to dig into the codebase and find the root cause. Let us know if you're still needing help on this!

ajaviles13 commented 1 week ago

Hi @cwomack, I haven't had a chance to dig deeper. I have my current Auth workflow working great with Supabase at the moment and I am heads down in other FE/BE dev priorities in order to launch an MVP app within the next month. I'm a one man band at the moment so I'll circle back to the AWS Auth implementation in late December once my MVP is out there with my beta users.

cwomack commented 6 days ago

@ajaviles13, completely understand and take your time! We'll update the labels to be pending your response until you get some bandwidth to dig deeper and keep the issue open. Feel free to reply back whenever you get a chance in December, and good luck!

ajaviles13 commented 1 day ago

Sounds good and will do. Thanks @cwomack !