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

Cannot access current authenticated user through Amplify Auth #10524

Closed llhyatt98 closed 1 year ago

llhyatt98 commented 2 years ago

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

``` # Put output below this line System: OS: macOS 12.4 CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz Memory: 417.94 MB / 16.00 GB Shell: 5.8.1 - /bin/zsh Binaries: Node: 14.18.1 - /usr/local/bin/node Yarn: 1.22.11 - /usr/local/bin/yarn npm: 6.14.15 - /usr/local/bin/npm Browsers: Chrome: 106.0.5249.119 Firefox: 91.0.2 Safari: 15.5 npmPackages: @aws-amplify/cli: ^9.2.1 => 9.2.1 @babel/core: ^7.18.6 => 7.19.6 (7.18.13, 7.9.0) @babel/plugin-proposal-decorators: 7.12.1 => 7.12.1 (7.18.10) @babel/plugin-proposal-optional-catch-binding: 7.12.1 => 7.12.1 (7.18.6) @babel/preset-env: ^7.16.11 => 7.18.10 @babel/runtime: ^7.12.5 => 7.18.9 (7.9.0, 7.16.7, 7.19.4) @expo/webpack-config: ^0.17.0 => 0.17.2 @react-native-async-storage/async-storage: ~1.17.3 => 1.17.10 @react-native-community/cli-platform-ios: ^6.2.0 => 6.2.1 (8.0.6) @react-native-community/netinfo: 9.3.0 => 9.3.0 @react-native-picker/picker: 2.4.2 => 2.4.2 @react-navigation/material-bottom-tabs: ^6.2.1 => 6.2.3 @react-navigation/native: ~6.0.1 => 6.0.12 @react-navigation/native-stack: ^6.0.2 => 6.8.0 @react-navigation/stack: ~6.0.1 => 6.0.11 @reduxjs/toolkit: ^1.8.2 => 1.8.5 @reduxjs/toolkit-query: 1.0.0 @reduxjs/toolkit-query-react: 1.0.0 @rneui/base: ^4.0.0-rc.3 => 4.0.0-rc.6 @rneui/themed: ^4.0.0-rc.3 => 4.0.0-rc.6 @rnx-kit/metro-config: ^1.2.31 => 1.2.36 @rnx-kit/metro-resolver-symlinks: ^0.1.15 => 0.1.21 @shopify/react-native-skia: 0.1.141 => 0.1.141 @storybook/react-native: 5.3.25 => 5.3.25 @storybook/react-native-server: 5.3.23 => 5.3.23 @types/i18n-js: 3.0.3 => 3.0.3 @types/jest: 26.0.19 => 26.0.19 @types/react: ~18.0.0 => 18.0.21 (17.0.48) @types/react-dom: ~18.0.0 => 18.0.6 @types/react-native: ~0.69.1 => 0.69.15 (0.69.5) @types/react-test-renderer: 17.0.1 => 17.0.1 @typescript-eslint/eslint-plugin: 4.10.0 => 4.10.0 @typescript-eslint/parser: 4.10.0 => 4.10.0 HelloWorld: 0.0.1 apisauce: 2.0.0 => 2.0.0 (0.14.3) aws-amplify: ^4.3.25 => 4.3.33 aws-amplify-react-native: ^6.0.5 => 6.0.5 babel-jest: 26.6.3 => 26.6.3 babel-loader: 8.2.2 => 8.2.2 (8.1.0) crypto-js: ^4.1.1 => 4.1.1 detox: 19.3.0 => 19.3.0 detox-expo-helpers: 0.6.0 => 0.6.0 eslint: 7.15.0 => 7.15.0 eslint-config-prettier: 7.0.0 => 7.0.0 eslint-config-standard: 16.0.2 => 16.0.2 eslint-plugin-import: 2.22.1 => 2.22.1 eslint-plugin-node: 11.1.0 => 11.1.0 eslint-plugin-promise: 4.2.1 => 4.2.1 eslint-plugin-react: 7.21.5 => 7.21.5 eslint-plugin-react-native: 3.10.0 => 3.10.0 expo: ^46.0.0 => 46.0.16 expo-auth-session: ~3.7.1 => 3.7.1 expo-cli: ^6.0.6 => 6.0.6 expo-crypto: ~11.0.0 => 11.0.0 expo-detox-hook: 1.0.10 => 1.0.10 expo-linear-gradient: ~11.4.0 => 11.4.0 expo-linking: ~3.2.2 => 3.2.2 expo-localization: ~13.1.0 => 13.1.0 expo-modules-autolinking: ~0.10.1 => 0.10.3 (0.8.1) expo-modules-core: ~0.11.8 => 0.11.8 expo-random: ~12.3.0 => 12.3.0 expo-sensors: ~11.4.0 => 11.4.0 expo-status-bar: ~1.4.0 => 1.4.0 expo-updates: ~0.14.6 => 0.14.6 fbjs-scripts: 3.0.0 => 3.0.0 hermes-inspector-msggen: 1.0.0 i18n-js: 3.8.0 => 3.8.0 jest: ^26.6.3 => 26.6.3 jest-circus: 26 => 26.6.3 jest-expo: ^46.0.0 => 46.0.1 jetifier: 1.6.6 => 1.6.6 (1.6.8) memo-parser: 0.2.1 metro-react-native-babel-preset: ^0.70.3 => 0.70.3 mobx: 6.1.8 => 6.1.8 mobx-react-lite: 3.2.0 => 3.2.0 mobx-state-tree: 5.0.1 => 5.0.1 moralis: ^1.8.0 => 1.11.0 patch-package: 6.2.2 => 6.2.2 postinstall-prepare: 1.0.1 => 1.0.1 prettier: 2.2.1 => 2.2.1 query-string: ^7.0.1 => 7.1.1 (5.1.1, 6.10.1) react: 18.0.0 => 18.0.0 (16.14.0) react-devtools-core: 4.10.1 => 4.10.1 (4.24.0) react-dom: 18.0.0 => 18.0.0 (16.14.0) react-moralis: ^1.4.0 => 1.4.1 react-native: 0.69.5 => 0.69.5 react-native-chart-kit: ^6.12.0 => 6.12.0 react-native-clean-project: ^3.6.3 => 3.6.7 react-native-dropdown-picker: ^5.4.2 => 5.4.2 react-native-elements: ^3.4.2 => 3.4.2 react-native-gesture-handler: ~2.5.0 => 2.5.0 react-native-graph: ^0.3.0 => 0.3.0 react-native-keychain: 6.2.0 => 6.2.0 react-native-paper: ^4.12.1 => 4.12.4 react-native-reanimated: ~2.9.1 => 2.9.1 react-native-safe-area-context: 4.3.1 => 4.3.1 react-native-screens: ~3.15.0 => 3.15.0 react-native-shadow-2: ^6.0.5 => 6.0.6 react-native-svg: 12.3.0 => 12.3.0 react-native-uuid: ^2.0.1 => 2.0.1 react-native-vector-icons: ^9.2.0 => 9.2.0 react-native-web: ~0.18.7 => 0.18.9 react-native-webview: 11.23.0 => 11.23.0 reactotron-core-client: ^2.8.10 => 2.8.10 (2.8.9) reactotron-mst: 3.1.4 => 3.1.4 reactotron-react-js: ^3.3.7 => 3.3.8 reactotron-react-native: 5.0.1 => 5.0.1 reanimated-bottom-sheet: ^1.0.0-alpha.22 => 1.0.0-alpha.22 solidarity: 2.3.1 => 2.3.1 ts-jest: 26 => 26.5.6 typescript: ^4.6.3 => 4.8.4 validate.js: 0.13.1 => 0.13.1 web3: ^1.7.3 => 1.7.5 npmGlobalPackages: @aws-amplify/cli: 10.0.0 @nestjs/cli: 7.5.4 amplify: 0.0.11 corepack: 0.10.0 cpx: 1.5.0 expo-cli: 6.0.6 firebase-tools: 8.16.1 gulp-cli: 2.3.0 n: 8.2.0 node-sass: 6.0.0 nodemon: 2.0.4 npm-run-all: 4.1.5 npm: 6.14.15 sass: 1.32.13 scss: 0.2.4 typescript: 3.9.7 yarn: 1.22.11 ```

Describe the bug

We are integrating with amplify authentication in our react native app (runs on expo). We can authenticated a user to sign up or log in at any time, but after logging in we cannot get current user data while they are in the app. The session data does not seem to be saving, there are related issues on this topic but none of which seem to have been closed.

Expected behavior

According to the docs, we should be able to access current user data once they have logged in through the Auth module.

Reproduction steps

This bug is triggered when we make a request to Auth.currentCredentials, Auth.currentUserInfo, Auth.currentUserCredentials etc... The error in the screenshot can be reproduced making that request.

Code Snippet

// Put your code below this line.
const logger = new Logger('foo', 'INFO');
logger.debug('callback data');
Auth.currentAuthenticatedUser(() => console.log(user))

Log output

``` // Put your logs below this line [DEBUG] 10:23.915 foo - callback data [DEBUG] 10:23.918 AuthClass - getting current authenticated user Fetching pedometer [DEBUG] 10:23.940 AuthClass - cannot load federated user from auth storage [DEBUG] 10:23.941 AuthClass - get current authenticated userpool user [DEBUG] 10:23.944 AuthClass - Failed to get user from user pool [DEBUG] 10:23.946 AuthClass - The user is not authenticated by the error No current user ```

aws-exports.js

const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_appsync_graphqlEndpoint": "https://gh5r3akrkbc6tb2nr7ryaxfgmm.appsync-api.us-east-1.amazonaws.com/graphql",
    "aws_appsync_region": "us-east-1",
    "aws_appsync_authenticationType": "API_KEY",
    "aws_appsync_apiKey": "da2-4nbstrfvszgormcpw4wvload3u",
    "aws_cognito_identity_pool_id": "us-east-1:ae09b592-6371-4adb-b8b0-3fb92b1ece3d",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_eakPQuatX",
    "aws_user_pools_web_client_id": "fosmcnp3u79co6i9l7pfifvp6",
    "oauth": {},
    "aws_cognito_username_attributes": [
        "EMAIL"
    ],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL"
    ],
    "aws_cognito_mfa_configuration": "ON",
    "aws_cognito_mfa_types": [
        "SMS",
        "TOTP"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 8,
        "passwordPolicyCharacters": [
            "REQUIRES_LOWERCASE",
            "REQUIRES_NUMBERS",
            "REQUIRES_SYMBOLS",
            "REQUIRES_UPPERCASE"
        ]
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

chrisbonifacio commented 2 years ago

Hi @llhyatt98 👋 thanks for raising this issue. A few questions:

  1. Can you confirm that after signing in you can see the cognito id, access, and refresh tokens in the local storage?
  2. Are there any errors being logged during or after logging in?
  3. Are you using the auth library directly to sign in or the withAuthenticator UI component?
llhyatt98 commented 2 years ago

Hi @chrisbonifacio - thanks for getting back on this. In response to each point:

  1. The object attached was the response from logging in. I believe there are options to store session data in local storage after login/signup - we are currently not doing anything with that response. It does not seem necessary as amplify auth can do this through the cache?
  2. No errors logged during login
  3. We are using the auth library directly.
tannerabread commented 2 years ago

@llhyatt98 Does the MFA you set up (SMS/TOTP) get triggered when you try this flow? Can you try the Amplify Logger on an app/component level to see what is shown when logging in? I realize you said there are no errors while logging in but I want to make sure there is success also

Amplify.Logger.LOG_LEVEL = 'DEBUG';
tannerabread commented 1 year ago

@llhyatt98 In regards to the 1st question @chrisbonifacio had asked, Amplify Auth automatically stores in AsyncStorage for React Native projects so you would need to look there.

I also noticed something small with this one that may or may not be your issue

Auth.currentAuthenticatedUser(() => console.log(user))

This (and all of the ones you mentioned) are async functions and can't be used like this to retrieve the credentials It would instead need to be used like the following

Auth.currentAuthenticatedUser()
    .then(user => console.log(user))
    .catch(err => console.log(err))
tannerabread commented 1 year ago

Hi 👋 Closing this as we have not heard back from you. If you are still experiencing this issue and are in need of assistance, please feel free to comment and provide us with any information previously requested by our team members so we can re-open this issue and be better able to assist you.

Thank you!

Haider-Ali-7 commented 1 year ago

Describe the bug I'm facing this issue on ios. I'm not getting any response while calling the currentAuthenticatedUser. I'm calling this function just as you shown. It works on android.

package.json

"aws-amplify": "^4.3.29", "react": "17.0.2", "react-native": "0.66.4"

aws-exports.js

const awsmobile = {
    "aws_project_region": "us-east-2",
    "aws_cognito_identity_pool_id": "us-east-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "aws_cognito_region": "us-east-2",
    "aws_user_pools_id": "us-east-2_xxxxxxxxx",
    "aws_user_pools_web_client_id": "31gs1iqkbeffj006j69odt5ns6",
    "oauth": {
        "domain": "myapp98xxxxxx-98xxxxxx-dev.auth.us-east-2.amazoncognito.com",
        "scope": [
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "myapp://",
        "redirectSignOut": "myapp://",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS",
    "aws_cognito_username_attributes": [
        "EMAIL",
        "PHONE_NUMBER"
    ],
    "aws_cognito_social_providers": [
        "FACEBOOK",
        "GOOGLE",
        "APPLE"
    ],
    "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;
tannerabread commented 1 year ago

Hi @Haider-Ali-7, would you mind giving a short code snippet of how you are using it and where

Haider-Ali-7 commented 1 year ago

I have used currentAuthenticatedUser function inside useEffect with or without side-effects. It didn't work.

import {Amplify, Auth, Hub} from 'aws-amplify';
import config from '../aws-exports';
import InAppBrowser from 'react-native-inappbrowser-reborn'

const urlOpener = async (url, redirectUrl) => {
   InAppBrowser.openAuth(url, redirectUrl, {
          dismissButtonStyle: 'cancel',
          showTitle: false,
          enableUrlBarHiding: true,
          enableDefaultShare: false,
          ephemeralWebSession: false,
        }).then((res) => {
        if (res === 'SUCCESS') {
            Linking.openURL(res.url);
          }
       }).catch(err => console.log("urlOpener err: ", err))
   }

Amplify.configure({
  ...config,
  oauth: {
    ...config.oauth,
    urlOpener 
  }
});

const Login = props => {
 useEffect(() => {
    const unsubscribe = Hub.listen('auth', ({payload: {event, data}}) => {
      switch (event) {
        case 'signIn':
          console.log('signIn', data);
          break;
        case 'signOut':
          console.log('sign out!');
          break;
        default:
          console.log("default User", data);
          break;
      }
    });

    return unsubscribe;
  }, []);

   Auth.currentAuthenticatedUser()
      .then(user => console.log("currentAuthenticatedUser", user))
      .catch((err) => console.log('currentAuthenticatedUser err: ', err));
}

export default Login;
tannerabread commented 1 year ago

@Haider-Ali-7 are your events firing and signin working when you login?

Also are you just running the function by itself inside of your component?

Haider-Ali-7 commented 1 year ago

Because right now we are configuring Identity provider pool Username attribute to have value other than id. I do get user details in pool if signIn on android device. SignIn doesn't fire on ios.

For function I have tested three ways:

const Login = props => {
 useEffect(() => {
    const unsubscribe = Hub.listen('auth', ({payload: {event, data}}) => {
      switch (event) {
        case 'signIn':
          console.log('signIn', data);
          break;
        case 'signOut':
          console.log('sign out!');
          break;
        default:
          console.log("default User", data);
          break;
      }
    });

   // called here currentAuthenticatedUser() ---didn't work

    return unsubscribe;
  }, []); //with sideeffects ---didn't work

  //right now calling currentAuthenticatedUser() here ---didn't work

}

export default Login;
tannerabread commented 1 year ago

Did you set up the Linking module in AppDelegate.m for this project? See docs on it here in the first note

Also is that line if (res === 'SUCCESS') { working properly? It's written different from the docs and I see what is trying to be done but I think if you go about it that way you would need to do if (res.type === 'success') {

Haider-Ali-7 commented 1 year ago

1 - Already Configured Linking 2 - if (res.type === 'success') { //Sorry I wrote the code wrong here.

It's not a solution. But more of a cleansing the project. It worked for me. Here what I did

yarn cache clean
pod cache clean
podfile.lock //deleted
pod install

Start the project. Now i'm getting the user details in ios too.🎉 You can close the issue. Thanks you for helping out.

tannerabread commented 1 year ago

Thank you @Haider-Ali-7 for detailing your solution in case anyone else finds this issue. If you have any other issues with Amplify, please feel free to open a new issue or join our discord channel for help from the community.

Thank you!