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.41k stars 2.11k forks source link

Authentication doesn't work propetly #9990

Closed IsmetGlumcevic closed 1 year ago

IsmetGlumcevic commented 2 years ago

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

GraphQL API

Amplify Categories

auth

Environment information

``` System: OS: macOS 12.2 CPU: (8) arm64 Apple M1 Memory: 95.70 MB / 8.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 16.15.1 - ~/.nvm/versions/node/v16.15.1/bin/node npm: 8.11.0 - ~/.nvm/versions/node/v16.15.1/bin/npm Watchman: 2022.06.06.00 - /opt/homebrew/bin/watchman Browsers: Chrome: 102.0.5005.115 Safari: 15.3 npmPackages: @babel/core: ^7.12.9 => 7.17.10 @babel/runtime: ^7.12.5 => 7.17.9 @klarna/react-native-vector-drawable: ^0.1.2 => 0.1.2 @react-native-async-storage/async-storage: ^1.17.4 => 1.17.4 @react-native-community/datetimepicker: ^6.1.3 => 6.1.3 @react-native-community/eslint-config: ^2.0.0 => 2.0.0 @react-native-community/netinfo: ^8.3.0 => 8.3.0 @react-native-picker/picker: ^2.4.1 => 2.4.1 @react-navigation/bottom-tabs: ^6.3.1 => 6.3.1 @react-navigation/native: ^6.0.10 => 6.0.10 @react-navigation/native-stack: ^6.6.2 => 6.6.2 @voximplant/react-native-foreground-service: ^3.0.1 => 3.0.1 HelloWorld: 0.0.1 amazon-cognito-identity-js: ^5.2.8 => 5.2.8 aws-amplify: ^4.3.21 => 4.3.21 aws-amplify-react-native: ^6.0.4 => 6.0.4 babel-jest: ^26.6.3 => 26.6.3 eslint: ^7.32.0 => 7.32.0 hermes-inspector-msggen: 1.0.0 jest: ^26.6.3 => 26.6.3 metro-react-native-babel-preset: ^0.67.0 => 0.67.0 react: 17.0.2 => 17.0.2 react-hook-form: ^7.30.0 => 7.30.0 react-native: 0.68.1 => 0.68.1 react-native-bootsplash: ^4.1.5 => 4.1.5 react-native-confirmation-code-field: ^7.3.0 => 7.3.0 react-native-fast-image: ^8.5.11 => 8.5.11 react-native-geolocation-service: ^5.3.0-beta.4 => 5.3.0-beta.4 react-native-image-picker: ^4.8.3 => 4.8.3 react-native-maps: ^0.31.1 => 0.31.1 react-native-modal-datetime-picker: ^13.1.2 => 13.1.2 react-native-phone-number-input: ^2.1.0 => 2.1.0 react-native-safe-area-context: ^4.2.5 => 4.2.5 react-native-screens: ^3.13.1 => 3.13.1 react-native-snap-carousel: ^3.9.1 => 3.9.1 react-native-vector-image: ^0.3.3 => 0.3.3 react-test-renderer: 17.0.2 => 17.0.2 npmGlobalPackages: @aws-amplify/cli: 8.4.0 corepack: 0.10.0 npm: 8.11.0 ```

Describe the bug

I use amplify auth with custom screens and react-navigation, signup and signin with phone and password, authentication doesn't work properly. When I am on mobile internet 4G it works well when I use my home wifi internet doesn't work, I see only loader, app cannot check if a user is logged in. Please help, the app is completed and needs to be published. I test on the simulator and on real devices in production.

This is auth context:

import React, {createContext, useState, useEffect} from 'react';
import {Hub, Auth} from 'aws-amplify';

export const AuthContext = createContext();

const AuthContextProvider = props => {
  const [user, setUser] = useState(undefined);

  const checkUser = async () => {
    try {
      const authUser = await Auth.currentAuthenticatedUser({
        bypassCache: true,
      });
      setUser(authUser);
    } catch (e) {
      console.log('e', e);
      setUser(null);
    }
  };

  useEffect(() => {
    checkUser();
  }, []);

  useEffect(() => {
    const listener = data => {
      if (data.payload.event === 'signIn' || data.payload.event === 'signOut') {
        checkUser();
      }
    };

    Hub.listen('auth', listener);
    return () => Hub.remove('auth', listener);
  }, []);

  return (
    <AuthContext.Provider
      value={{
        user,
             }}>
      {props.children}
    </AuthContext.Provider>
  );
};

export default AuthContextProvider;

This is nav file:

import React, {useContext} from 'react';
import MainNav from 'src/pages/navigation/main';
import AuthNav from 'src/pages/navigation/auth';
import Loader from 'src/pages/navigation/loader';
import {AuthContext} from 'src/context/AuthContext';

const Navigation = () => {
  const {user} = useContext(AuthContext);
  if (user === undefined) {
    return <Loader />;
  }

  return <>{user ? <MainNav /> : <AuthNav />}</>;
};

export default Navigation;

Expected behavior

I expect to work on all internet networks.

Reproduction steps

  1. install auth
  2. add custom screens
  3. add auth context and navigation
  4. check on different networks

aws-exports.js

const awsmobile = {
    "aws_project_region": "eu-central-1",
    "aws_cognito_identity_pool_id": "eu-central-1:1f7a5eae-b372-4be0-aa0b-4743343f2f2a",
    "aws_cognito_region": "eu-central-1",
    "aws_user_pools_id": "eu-central-1_izllRSrUJ",
    "aws_user_pools_web_client_id": "358dhb3u7qr6sdj2bphdu2nq03",
    "oauth": {},
    "aws_cognito_username_attributes": [
        "PHONE_NUMBER"
    ],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "PHONE_NUMBER"
    ],
    "aws_cognito_mfa_configuration": "ON",
    "aws_cognito_mfa_types": [
        "SMS",
        "TOTP"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 6,
        "passwordPolicyCharacters": [
            "REQUIRES_UPPERCASE"
        ]
    },
    "aws_cognito_verification_mechanisms": [
        "PHONE_NUMBER"
    ],
    "aws_appsync_graphqlEndpoint": "https://3sgbvkdwazgxzme7fehbl5xkhi.appsync-api.eu-central-1.amazonaws.com/graphql",
    "aws_appsync_region": "eu-central-1",
    "aws_appsync_authenticationType": "API_KEY",
    "aws_appsync_apiKey": "da2-fsmvbp6hlfhgji6dlspubgmfma",
    "aws_user_files_s3_bucket": "ellwyservices3db14c6a175c4e86a6b3716692603517140445-dev",
    "aws_user_files_s3_bucket_region": "eu-central-1"
};

export default awsmobile;
chrisbonifacio commented 2 years ago

Hi @IsmetGlumcevic 👋 Sorry you are experiencing this issue. Just a few questions to get a better understanding and/or to help unblock you.

  1. Is there any particular reason why you are using bypassCache: true in Auth.currentAuthenticatedUser()? It's going to make a request to Cognito for the latest user data but is not required to check for authentication. Is this intended?
  2. Have you considered using the @aws-amplify/ui-react package's Authenticator.Provider and useAuthenticator hook to keep track of auth state? This might help simplify the management of Amplify's auth state in your app and facilitate rendering the correct views. For more information: https://ui.docs.amplify.aws/react/components/authenticator/headless#useauthenticator-hook
IsmetGlumcevic commented 2 years ago

I need latest user data because I'm checking user for setup profile. If this is a problem I can check user from database. Does Authenticator.Provider and useAuthenticator work with react native? I have custom design and need to have custom screens.

chrisbonifacio commented 2 years ago

I need latest user data because I'm checking user for setup profile. If this is a problem I can check user from database. Does Authenticator.Provider and useAuthenticator work with react native? I have custom design and need to have custom screens.

My apologies, I forgot you were using React Native from the code snippets. Disregard my question about the @aws-amplify/ui-react package, that is intended for React web applications. The withAuthenticator higher-order component is recommended for React Native.

abdallahshaban557 commented 2 years ago

@IsmetGlumcevic - we are planning to re-write the Authenticator for React Native, and the useAuthenticator hook is planned to also work for it. In the meantime, you can use the Auth.currentAuthenticatedUser() to check for a current user signed in to your app.

chrisbonifacio commented 2 years ago

Just to follow up on this issue, I've created a React Native app with a custom auth ui and, using the auth provider code snippet you provided, did not notice any issues logging in. I tried on my phone (5G) and on my home wifi (1gbps down/up).

When testing on your home wifi, are you not able to login at all? Can you see if there is any network activity such as a request to Cognito that might be timing out?

Also, you can enable logging for Amplify by adding this line to your index.js file.

Amplify.Logger.LOG_LEVEL = "DEBUG"

and share any logs that are printed when you experience the issue.

IsmetGlumcevic commented 2 years ago

I can't login, the page freezes and get logs:

DEBUG] 20:51.837 AuthClass CognitoUserSession {idToken: CognitoIdToken, refreshToken: CognitoRefreshToken, accessToken: CognitoAccessToken, clockDrift: 0}accessToken: CognitoAccessTokenjwtToken:….. ConsoleLogger.js:127 [DEBUG] 20:51.839 Credentials - removing aws-amplify-federatedInfo from storage ConsoleLogger.js:127 [DEBUG] 20:51.840 Credentials - set credentials from session (it stops here)

When I logged in, can't check is user authenticated, the page freezes , get log:

[DEBUG] 26:29.735 AuthClass - getting current authenticated user ConsoleLogger.js:127 [DEBUG] 26:29.757 AuthClass - cannot load federated user from auth storage ConsoleLogger.js:127 [DEBUG] 26:29.757 AuthClass - get current authenticated userpool user (it stops here)

On mobile internet work well(5G). Home wifi doesn't work (10Mbps down/up). Sometimes it looks like it was successful login but it can't fetch data from api. Sometimes works on home wifi, when I have a fresh install app. I see there is a token expiration time of 1 hour. Is possible that the issue is with token expiration? Maybe can't fetch tokens from storage when wifi is slow?

IsmetGlumcevic commented 2 years ago

Full log when user is successfully login:

[DEBUG] 45:41.991 AuthClass - getting current authenticated user ConsoleLogger.js:127 [DEBUG] 45:42.21 AuthClass - cannot load federated user from auth storage ConsoleLogger.js:127 [DEBUG] 45:42.21 AuthClass - get current authenticated userpool user ConsoleLogger.js:139 [DEBUG] 45:42.27 RestAPI - API Options null ConsoleLogger.js:139 [DEBUG] 45:42.27 Amplify - component registered in amplify RestAPIClass {_api: null, Credentials: CredentialsClass, _options: null} ConsoleLogger.js:139 [DEBUG] 45:42.28 RestAPI - configure Rest API {opt: {…}} ConsoleLogger.js:127 [DEBUG] 45:42.28 RestAPI - create Rest API instance ConsoleLogger.js:139 [DEBUG] 45:42.29 RestClient - API Options {aws_project_region: 'eu-central-1', aws_cognito_identity_pool_id: ‘xxxx’, aws_cognito_region: 'eu-central-1', aws_user_pools_id: 'xxx', aws_user_pools_web_client_id: ‘cxxxx’, …} ConsoleLogger.js:139 [DEBUG] 45:42.30 RestAPI - API Options null ConsoleLogger.js:139 [DEBUG] 45:42.31 PubSub - PubSub Options {} ConsoleLogger.js:139 [DEBUG] 45:42.32 Amplify - component registered in amplify PubSubClass {_options: {…}, _pluggables: Array(0), subscribe: ƒ} ConsoleLogger.js:139 [DEBUG] 45:42.32 PubSub - configure PubSub {opt: {…}} ConsoleLogger.js:139 [DEBUG] 45:42.32 GraphQLAPI - API Options null ConsoleLogger.js:139 [DEBUG] 45:42.32 Amplify - component registered in amplify GraphQLAPIClass {_api: null, Auth: AuthClass, Cache: AsyncStorageCache, Credentials: CredentialsClass, _options: null} ConsoleLogger.js:139 [DEBUG] 45:42.33 GraphQLAPI - configure GraphQL API {opt: {…}} ConsoleLogger.js:127 [DEBUG] 45:42.33 GraphQLAPI - create Rest instance ConsoleLogger.js:139 [DEBUG] 45:42.33 RestClient - API Options {aws_project_region: 'eu-central-1', aws_cognito_identity_pool_id: ‘xxxxx’xx, aws_cognito_region: 'eu-central-1', aws_user_pools_id: 'xxx', aws_user_pools_web_client_id: ‘xxxxxxxx’, …} ConsoleLogger.js:139 [DEBUG] 45:42.33 GraphQLAPI - API Options null ConsoleLogger.js:139 [DEBUG] 45:42.33 API - API Options null ConsoleLogger.js:139 [DEBUG] 45:42.33 Amplify - component registered in amplify APIClass {Auth: AuthClass, Cache: AsyncStorageCache, Credentials: CredentialsClass, _options: null, _restApi: RestAPIClass, …} ConsoleLogger.js:139 [DEBUG] 45:42.34 RestAPI - configure Rest API {opt: {…}} ConsoleLogger.js:127 [DEBUG] 45:42.34 RestAPI - create Rest API instance ConsoleLogger.js:139 [DEBUG] 45:42.34 RestClient - API Options {aws_project_region: 'eu-central-1', aws_cognito_identity_pool_id: ‘xxxx, aws_cognito_region: 'eu-central-1', aws_user_pools_id: 'xxx', aws_user_pools_web_client_id: ‘xxxxx’, …} ConsoleLogger.js:139 [DEBUG] 45:42.34 GraphQLAPI - configure GraphQL API {opt: {…}} ConsoleLogger.js:127 [DEBUG] 45:42.34 GraphQLAPI - create Rest instance ConsoleLogger.js:139 [DEBUG] 45:42.35 RestClient - API Options {aws_project_region: 'eu-central-1', aws_cognito_identity_pool_id: 'exxxxxxx’, aws_cognito_region: 'eu-central-1', aws_user_pools_id: 'xxx', aws_user_pools_web_client_id: ‘xxxxxx’, …} ConsoleLogger.js:139 [DEBUG] 45:42.177 RestClient - POST https://xxx-api.eu-central-1.amazonaws.com/graphql ConsoleLogger.js:127 [DEBUG] 45:45.610 AuthClass - getting current authenticated user ConsoleLogger.js:127 [DEBUG] 45:45.639 AuthClass - cannot load federated user from auth storage ConsoleLogger.js:127 [DEBUG] 45:45.640 AuthClass - get current authenticated userpool user ConsoleLogger.js:139 [DEBUG] 45:45.661 RestClient - POST https://xxx-api.eu-central-1.amazonaws.com/graphql ConsoleLogger.js:139 [DEBUG] 45:45.710 RestClient - POST https://xxx-api.eu-central-1.amazonaws.com/graphql ConsoleLogger.js:139 [DEBUG] 45:45.713 RestClient - POST https://xxx-api.eu-central-1.amazonaws.com/graphql ConsoleLogger.js:139 [DEBUG] 45:46.624 RestClient - POST https://xxx-api.eu-central-1.amazonaws.com/graphql profileSetupScreen.js:103 file: User already exists in DB ConsoleLogger.js:127 [DEBUG] 45:52.479 Storage - Create Storage Instance, debug ConsoleLogger.js:139 [DEBUG] 45:52.480 StorageClass - Storage Options {} ConsoleLogger.js:139 [DEBUG] 45:52.481 StorageClass - Storage Options {} ConsoleLogger.js:139 [DEBUG] 45:52.481 Amplify - component registered in amplify Storage {_config: {…}, _pluggables: Array(0), _cancelTokenSourceMap: WeakMap, get: ƒ, put: ƒ, …} ConsoleLogger.js:127 [DEBUG] 45:52.481 Storage - storage configure called ConsoleLogger.js:127 [DEBUG] 45:52.482 StorageClass - configure Storage ConsoleLogger.js:139 [DEBUG] 45:52.482 Parser - parse config (3) [{…}, 'to amplifyconfig', {…}] ConsoleLogger.js:139 [DEBUG] 45:52.483 AWSS3Provider - Storage Options {} ConsoleLogger.js:139 [DEBUG] 45:52.484 AWSS3Provider - configure Storage {bucket: 'xxx-dev', region: 'eu-central-1', dangerouslyConnectToHttpEndpointForTesting: undefined} ConsoleLogger.js:139 [DEBUG] 45:52.484 Parser - parse config (3) [{…}, 'to amplifyconfig', {…}] ConsoleLogger.js:127 [DEBUG] 45:52.484 Storage - storage vault configure called ConsoleLogger.js:127 [DEBUG] 45:52.485 StorageClass - configure Storage ConsoleLogger.js:139 [DEBUG] 45:52.485 Parser - parse config (3) [{…}, 'to amplifyconfig', {…}] ConsoleLogger.js:139 [DEBUG] 45:52.485 AWSS3Provider - Storage Options {} ConsoleLogger.js:139 [DEBUG] 45:52.486 AWSS3Provider - configure Storage {bucket: 'xxx-dev', region: 'eu-central-1', dangerouslyConnectToHttpEndpointForTesting: undefined, level: 'private'} ConsoleLogger.js:139 [DEBUG] 45:52.486 Parser - parse config (3) [{…}, 'to amplifyconfig', {…}] ConsoleLogger.js:127 [DEBUG] 45:52.487 Credentials - getting credentials ConsoleLogger.js:127 [DEBUG] 45:52.487 Credentials - picking up credentials ConsoleLogger.js:127 [DEBUG] 45:52.488 Credentials - getting new cred promise ConsoleLogger.js:127 [DEBUG] 45:52.488 Credentials - checking if credentials exists and not expired ConsoleLogger.js:127 [DEBUG] 45:52.488 Credentials - need to get a new credential or refresh the existing one ConsoleLogger.js:127 [DEBUG] 45:52.489 Credentials - no credentials for expiration check ConsoleLogger.js:127 [DEBUG] 45:52.489 AuthClass - Getting current user credentials ConsoleLogger.js:139 [DEBUG] 45:52.490 AuthClass - failed to get or parse item aws-amplify-federatedInfo SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at AuthClass. (Auth.js:1639:50) at step (tslib.js:141:27) at Object.next (tslib.js:122:57) at fulfilled (tslib.js:112:62) at tryCallOne (core.js:37:12) at core.js:123:15 at JSTimers.js:248:18 at _callTimer (JSTimers.js:112:7) at _callReactNativeMicrotasksPass (JSTimers.js:162:5) ConsoleLogger.js:127 [DEBUG] 45:52.490 AuthClass - Getting current session ConsoleLogger.js:139 [DEBUG] 45:52.491 AuthClass - Getting the session from this user: CognitoUser {username: '4d82ea39-0d6d-40d2-9f08-ddcfab8b936d', pool: CognitoUserPool, Session: null, client: Client, signInUserSession: CognitoUserSession, …} ConsoleLogger.js:139 [DEBUG] 45:52.492 AuthClass - Succeed to get the user session CognitoUserSession {idToken: CognitoIdToken, refreshToken: CognitoRefreshToken, accessToken: CognitoAccessToken, clockDrift: 0} ConsoleLogger.js:139 [DEBUG] 45:52.492 AuthClass - getting session success CognitoUserSession {idToken: CognitoIdToken, refreshToken: CognitoRefreshToken, accessToken: CognitoAccessToken, clockDrift: 0} ConsoleLogger.js:127 [DEBUG] 45:52.492 Credentials - set credentials from session ConsoleLogger.js:139 [DEBUG] 45:52.954 Credentials - Load credentials successfully {accessKeyId: 'xxx', secretAccessKey: 'xxx', sessionToken: 'IQoJb3JpZ2luX2VjEHYaDGV1LWNlbnRyYWwtMSJGMEQCIDITLI…+2KicF02BMvYBpKJpGMoUU0TIxmQPvh1E78OZizt5AxRkCqv1', expiration: Fri Jun 24 2022 16:45:52 GMT+0200 (Central European Summer Time), identityId: 'eu-central-1:xxx'} ConsoleLogger.js:139 [DEBUG] 45:52.954 AWSS3Provider - set credentials for storage {accessKeyId: 'xxx', sessionToken: 'IQoJb3JpZ2luX2VjEHYaDGV1LWNlbnRyYWwtMSJGMEQCIDITLI…+2KicF02BMvYBpKJpGMoUU0TIxmQPvh1E78OZizt5AxRkCqv1', secretAccessKey: 'xxx', identityId: 'eu-central-1:xxx', authenticated: true} ConsoleLogger.js:127 [DEBUG] 45:52.965 AWSS3Provider - get ee5efbbe-5efc-42a9-912c-36e8a8ebb0be from public/ee5efbbe-5efc-42a9-912c-36e8a8ebb0be ConsoleLogger.js:127 [DEBUG] 45:52.970 Credentials - getting credentials ConsoleLogger.js:127 [DEBUG] 45:52.970 Credentials - picking up credentials ConsoleLogger.js:127 [DEBUG] 45:52.970 Credentials - getting new cred promise ConsoleLogger.js:127 [DEBUG] 45:52.970 Credentials - checking if credentials exists and not expired ConsoleLogger.js:139 [DEBUG] 45:52.971 Credentials - are these credentials expired? {accessKeyId: 'xxx', secretAccessKey: 'xxx', sessionToken: 'IQoJb3JpZ2luX2VjEHYaDGV1LWNlbnRyYWwtMSJGMEQCIDITLI…+2KicF02BMvYBpKJpGMoUU0TIxmQPvh1E78OZizt5AxRkCqv1', expiration: Fri Jun 24 2022 16:45:52 GMT+0200 (Central European Summer Time), identityId: 'eu-central-1:xxx', …} ConsoleLogger.js:127 [DEBUG] 45:52.971 Credentials - credentials not changed and not expired, directly return ConsoleLogger.js:139 [DEBUG] 45:52.971 S3ClientUtils - credentials provider get credentials {accessKeyId: 'xxx', sessionToken: 'IQoJb3JpZ2luX2VjEHYaDGV1LWNlbnRyYWwtMSJGMEQCIDITLI…+2KicF02BMvYBpKJpGMoUU0TIxmQPvh1E78OZizt5AxRkCqv1', secretAccessKey: 'xxx', identityId: 'eu-central-1:xxx', authenticated: true}

IsmetGlumcevic commented 2 years ago

@abdallahshaban557 - when we can expect a new authenticator for react native? Thanks.

calebpollman commented 2 years ago

Hi @IsmetGlumcevic!

We do not have a definitive release date for the new React Native Authenticator component but you can track progress by following issue #945 in the Amplify UI repo

Qruiser commented 1 year ago

Just realised this issue is so common, I raised it again here: https://github.com/aws-amplify/amplify-js/issues/10405. I am unable to use Storage.get because of this reason. Strangely it happens only on IOS.

tannerabread commented 1 year ago

@IsmetGlumcevic I noticed you have RN version 0.68 for this project which offered Fabric as opt-in. Was Fabric enabled on this project?

tannerabread commented 1 year ago

Hi :wave: Closing this in favor of the above mentioned issue#945 in the UI repo

mattsoftware commented 1 year ago

Above mentioned link is a 404 :/