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.12k forks source link

No current user error #8964

Closed RomanBob123 closed 2 years ago

RomanBob123 commented 2 years ago

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

``` System: OS: Linux 5.11 Ubuntu 20.04.2 LTS (Focal Fossa) CPU: (6) x64 Intel(R) Core(TM) i5-9600K CPU @ 3.70GHz Memory: 703.03 MB / 15.31 GB Container: Yes Shell: 5.0.17 - /bin/bash Binaries: Node: 10.24.1 - ~/.nvm/versions/node/v10.24.1/bin/node Yarn: 1.22.5 - /usr/bin/yarn npm: 6.14.12 - ~/.nvm/versions/node/v10.24.1/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Browsers: Chrome: 90.0.4430.85 Firefox: 92.0 npmPackages: @babel/core: ^7.9.6 => 7.14.6 @babel/plugin-proposal-class-properties: ^7.12.1 => 7.14.5 @babel/plugin-proposal-optional-chaining: ^7.6.0 => 7.14.5 @babel/runtime: ^7.9.6 => 7.14.6 @commitlint/cli: ^7.5.2 => 7.6.1 @commitlint/config-conventional: ^7.5.0 => 7.6.0 @mapbox/polyline: ^1.1.0 => 1.1.1 @react-native-async-storage/async-storage: ^1.15.4 => 1.15.5 @react-native-community/clipboard: ^1.2.3 => 1.5.1 @react-native-community/eslint-config: ^2.0.0 => 2.0.0 @react-native-community/geolocation: ^2.0.2 => 2.0.2 @react-native-community/masked-view: ^0.1.6 => 0.1.11 @react-native-community/netinfo: ^5.9.10 => 5.9.10 @react-native-community/progress-bar-android: ^1.0.3 => 1.0.4 @react-native-community/progress-view: ^1.0.3 => 1.3.1 @react-native-community/toolbar-android: git://github.com/react-native-community/toolbar-android.git => 0.2.1 @react-native-firebase/app: ^8.3.1 => 8.4.7 @react-native-firebase/crashlytics: ^8.3.4 => 8.5.2 @sentry/react-native: ^1.8.2 => 1.9.0 @twotalltotems/react-native-otp-input: ^1.1.0 => 1.3.11 @types/d3-shape: ^1.3.1 => 1.3.8 @types/jest: ^26.0.15 => 26.0.24 @types/lodash: ^4.14.134 => 4.14.171 @types/mapbox__polyline: ^1.0.0 => 1.0.2 @types/ramda: ^0.26.9 => 0.26.44 @types/react: ^16.8.14 => 16.14.11 (17.0.14) @types/react-native: ^0.57.49 => 0.57.65 (0.64.11) @types/react-native-app-link: ^1.0.0 => 1.0.0 @types/react-native-i18n: ^2.0.0 => 2.0.0 @types/react-native-modalbox: ^1.4.8 => 1.4.8 @types/react-native-phone-input: ^0.2.1 => 0.2.1 @types/react-native-snap-carousel: ^3.8.2 => 3.8.4 @types/react-native-tab-view: ^2.3.0 => 2.3.0 @types/react-native-vector-icons: ^6.4.0 => 6.4.8 @types/react-native-version-check: ^3.4.0 => 3.4.1 @types/react-navigation-material-bottom-tabs: ^0.3.1 => 0.3.2 @types/react-redux: ^7.1.0 => 7.1.17 @types/react-test-renderer: 16.0.3 => 16.0.3 @types/react-timeout: ^1.1.1 => 1.1.1 @types/redux-persist: ^4.3.1 => 4.3.1 @types/seamless-immutable: ^7.1.10 => 7.1.16 @types/styled-components: ^5.1.9 => 5.1.11 @types/underscore: ^1.9.0 => 1.11.3 @types/utm: ^1.1.0 => 1.1.1 @typescript-eslint/eslint-plugin: ^4.5.0 => 4.28.2 (3.10.1) @typescript-eslint/parser: ^4.5.0 => 4.28.2 (3.10.1) BasicExample: 0.0.1 CustomLibraryPicker: 0.0.1 CustomPicker: 0.0.1 HelloWorld: 0.0.1 PDFExample: 0.0.1 Sample: 0.0.1 amazon-cognito-identity-js: ^5.0.2 => 5.0.3 app-icon: ^0.6.3 => 0.6.4 appcenter: 2.6.1 => 2.6.1 appcenter-analytics: 2.6.1 => 2.6.1 appcenter-crashes: 2.6.1 => 2.6.1 aws-amplify: ^4.0.3 => 4.1.2 axios: ^0.18.1 => 0.18.1 (0.21.1) axios-retry: ^3.1.9 => 3.1.9 babel-core: ^7.0.0-bridge.0 => 7.0.0-bridge.0 (6.26.3) babel-jest: ^26.6.3 => 26.6.3 colors: ^1.3.3 => 1.4.0 commit-prompt: ^2.2.1 => 2.2.1 crypto-js: ^3.3.0 => 3.3.0 d3-force: ^2.0.1 => 2.1.1 d3-random: ^2.0.0 => 2.2.2 d3-shape: ^1.3.5 => 1.3.7 dotenv: ^8.0.0 => 8.6.0 eslint: ^7.11.0 => 7.30.0 eslint-config-prettier: ^6.14.0 => 6.15.0 eslint-plugin-prettier: ^3.1.4 => 3.4.0 (3.1.2) eslint-plugin-react: ^7.21.5 => 7.24.0 eslint-plugin-react-native: ^3.10.0 => 3.11.0 formik: ^2.2.9 => 2.2.9 fs: 0.0.1-security => 0.0.1-security hermes-inspector-msggen: 1.0.0 husky: ^1.3.1 => 1.3.1 i18n-parser: ^1.0.0 => 1.0.0 jest: ^26.6.3 => 26.6.3 jetifier: ^1.6.5 => 1.6.8 lint-staged: ^8.1.5 => 8.2.1 lodash: ^4.17.11 => 4.17.21 (4.17.11) lottie-ios: ^3.1.3 => 3.2.3 lottie-react-native: ^3.3.2 => 3.5.0 metro-react-native-babel-preset: ^0.55.0 => 0.55.0 (0.56.4) mitt: ^1.1.3 => 1.2.0 (1.1.3) moment: ^2.24.0 => 2.29.1 patch-package: ^6.2.2 => 6.4.7 prettier: ^1.19.1 => 1.19.1 (2.3.2) prop-types: ^15.7.2 => 15.7.2 (15.5.8, 15.6.2) ramda: ^0.26.1 => 0.26.1 react: 16.9.0 => 16.9.0 react-animated: 0.1.0 react-dom: ^16.8.6 => 16.14.0 react-native: 0.61.5 => 0.61.5 react-native-animatable: ^1.3.2 => 1.3.3 react-native-app-intro-slider: ^4.0.4 => 4.0.4 react-native-app-link: ^1.0.0 => 1.0.1 react-native-calendar-strip: ^2.0.7 => 2.2.3 react-native-calendars: ^1.403.0 => 1.1264.0 react-native-camera: ^3.44.1 => 3.44.3 react-native-chart-kit: ^6.6.1 => 6.11.0 react-native-circular-progress: ^1.1.0 => 1.3.7 react-native-collapsible: ^1.4.0 => 1.6.0 react-native-config: ^0.11.7 => 0.11.7 react-native-country-flags: ^1.1.0 => 1.1.0 react-native-country-picker-modal: ^1.8.1 => 1.11.0 react-native-dark-mode: ^0.2.2 => 0.2.2 react-native-device-info: ^5.5.3 => 5.6.5 react-native-disable-battery-optimizations-android: ^1.0.7 => 1.0.7 react-native-dropdown-picker: ^3.7.1 => 3.8.3 react-native-exit-app: ^1.1.0 => 1.1.0 react-native-fs: ^2.18.0 => 2.18.0 react-native-gesture-handler: ^1.5.3 => 1.10.3 react-native-gifted-chat: ^0.16.3 => 0.16.3 react-native-i18n: ~2.0.12 => 2.0.15 react-native-image-picker: ^4.0.3 => 4.0.4 react-native-interactable: ^2.0.1 => 2.0.1 react-native-iphone-x-helper: ^1.2.1 => 1.3.1 react-native-linear-gradient: ^2.5.6 => 2.5.6 react-native-localize: ^1.4.0 => 1.4.3 react-native-maps: 0.26.1 => 0.26.1 react-native-modal: ^11.5.6 => 11.10.0 react-native-modalbox: ^1.7.1 => 1.7.1 react-native-notifications: ^3.4.1 => 3.5.0 react-native-paper: ^2.15.2 => 2.16.0 react-native-pdf: ^6.0.0 => 6.3.0 react-native-permissions: ^2.0.9 => 2.2.2 react-native-phone-input: ^0.2.4 => 0.2.4 react-native-progress: ^3.6.0 => 3.6.0 react-native-ratings: ^7.3.0 => 7.6.1 react-native-reanimated: 1.9.0 => 1.9.0 react-native-responsive-screen: ^1.2.2 => 1.4.2 react-native-restart: 0.0.17 => 0.0.17 react-native-safe-area-context: ^0.6.2 => 0.6.4 react-native-safe-area-view: ^1.0.0 => 1.1.1 (0.14.9, 0.12.0) react-native-screens: ^2.0.0-alpha.25 => 2.18.1 react-native-segmented-control-tab: ^3.4.0 => 3.4.1 react-native-smart-tip: ^2.0.1 => 2.3.0 react-native-snap-carousel: ^3.9.1 => 3.9.1 react-native-sound: ^0.11.0 => 0.11.0 react-native-splash-screen: ^3.2.0 => 3.2.0 react-native-svg: ^12.1.1 => 12.1.1 react-native-svg-animations: ^0.1.9 => 0.1.9 react-native-svg-charts: ^5.4.0 => 5.4.0 react-native-svg-transformer: ^0.14.3 => 0.14.3 react-native-text-ticker: ^1.11.0 => 1.13.0 react-native-timezone: ^1.0.3 => 1.0.3 react-native-vector-icons: ^6.6.0 => 6.7.0 (7.1.0) react-native-version-check: ^3.4.1 => 3.4.2 react-native-walkthrough: git://github.com/danielwinkler/react-native-walkthrough#feature/PR-ts-element-multi-use => 0.2.0 react-native-walkthrough-tooltip: ^0.6.0 => 0.6.1 (1.1.7) react-navigation: ^4.0.10 => 4.4.4 react-navigation-material-bottom-tabs: ^1.1.1 => 1.1.1 react-navigation-stack: ^2.0.15 => 2.10.4 react-navigation-tabs: ^2.7.0 => 2.11.1 (1.2.0) react-redux: ^7.1.0 => 7.2.4 react-test-renderer: 16.6.3 => 16.6.3 react-timeout: ^1.2.0 => 1.2.0 reactotron-react-native: ^3.4.0 => 3.7.1 reactotron-redux: ^3.1.1 => 3.1.3 redux: ^4.0.1 => 4.1.0 redux-axios-middleware: ^4.0.0 => 4.0.1 redux-mock-store: ^1.5.4 => 1.5.4 redux-persist: ^5.10.0 => 5.10.0 redux-persist-transform-filter: 0.0.20 => 0.0.20 redux-persist/integration/react: undefined () redux-thunk: ^2.3.0 => 2.3.0 responsive-screen: 0.1.0 responsive-screen-orientation-change: 0.1.0 responsive-screen-styled-components: 0.1.0 rimraf: ^2.6.3 => 2.7.1 (3.0.2, 2.2.8) rn-fetch-blob: ^0.11.2 => 0.11.2 rn-placeholder: ^2.0.0 => 2.0.0 seamless-immutable: ^7.1.4 => 7.1.4 sendbird: 3.0.103 => 3.0.103 src: undefined () styled-components: ^5.2.1 => 5.3.0 styled-components/macro: undefined () styled-components/native: undefined () styled-components/primitives: undefined () svg-path-properties: ^0.5.2 => 0.5.2 (0.4.11) tslib: ^2.0.1 => 2.3.0 (1.14.1) typescript: ^3.9.3 => 3.9.10 underscore.string: ^3.3.5 => 3.3.5 utm: ^1.1.1 => 1.1.1 yup: ^0.32.9 => 0.32.9 (0.27.0) npmGlobalPackages: npm: 6.14.12 ```

Describe the bug

Sometimes for some reason we get an "No current user" error.

Expected behavior

No error

Reproduction steps

During token update

Code Snippet

const data = (await Auth.currentSession()).getIdToken();
const token = data.getJwtToken();

Log output

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

aws-exports.js

No response

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

Good day!

Our users get an error from time to time when trying to update a token. We update the token like this:

const data = (await Auth.currentSession()).getIdToken(); ... = data.getJwtToken();

Basically, there are no problems with this, but sometimes for some reason we get an "No current user" error.

Please tell me how can I fix this behavior?

chrisbonifacio commented 2 years ago

Hi @RomanBob123 Because the issue seems to happen intermittently, we're going to need more information in order to reproduce it consistently or be able to tell what might be going on. If you can get the error to occur again, please capture the network request and response or any relevant information from the console.

If you are able to reproduce this locally, please add this line to your project where you are configuring Amplify so that it can provide some more insight into what's happening within the Amplify instance through the debug console.

Amplify.Logger.LOG_LEVEL = "DEBUG";
chrisbonifacio commented 2 years ago

@RomanBob123 Can you confirm whether the users experiencing this issue might be authenticating through a social provider? If so, please share the code that shows how the oauth flow is implemented in the app.

This older issue might be relevant: https://github.com/aws-amplify/amplify-js/issues/399

RomanBob123 commented 2 years ago

This is how I update the token

`

const isConnected = (await NetInfo.fetch()).isConnected;
if (isConnected) {
  const data = (await Auth.currentSession()).getIdToken();
  const token = data.getJwtToken();
  return token;
}

`

RomanBob123 commented 2 years ago

We turned on debug and are trying to track it, but this does not happen regularly.

we are not using federation but are but a cognito user pool.

RomanBob123 commented 2 years ago

When the application starts, the amplify is configured:

Amplify.configure({
      Auth: {
        region: Config.REGION,
        userPoolId: Config.USER_POOL_ID,
        userPoolWebClientId: Config.USER_POOL_WEB_CLIENT_ID,
      },
    });

User login:

`

Auth.configure({
  authenticationFlowType: "USER_PASSWORD_AUTH",
});
const cognitoUser = await Auth.signIn(username, password);

`

chrisbonifacio commented 2 years ago

Hi @RomanBob123 👋 are you still experiencing this issue? If so, have you been able to capture what the Amplify debug logs and/or network requests might've looked like?

HiramYong commented 2 years ago

Meet this issue as well

RomanBob123 commented 2 years ago

Hi @RomanBob123 wave are you still experiencing this issue? If so, have you been able to capture what the Amplify debug logs and/or network requests might've looked like?

Yea. We still have it sometimes.

RomanBob123 commented 2 years ago

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

console error: No current user { arguments: ["error:","No current user"], logger: console } debug 10:35:12

vdhpieter commented 2 years ago

@chrisbonifacio We also have this issue.here are our debug logs:

[ERROR] 26:35.406 AuthClass - No current user
[DEBUG] 26:35.406 AuthClass - Failed to get user from user pool
[DEBUG] 26:35.405 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.405 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.405 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.405 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.405 AnalyticsClass - on hub capsule auth The Auth category has been configured successfully
[DEBUG] 26:35.405 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.404 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.404 Parser - parse config
[DEBUG] 26:35.404 AuthClass - configure Auth
[DEBUG] 26:35.403 RestClient - API Options
[DEBUG] 26:35.403 GraphQLAPI - create Rest instance
[DEBUG] 26:35.403 GraphQLAPI - configure GraphQL API
[DEBUG] 26:35.403 RestClient - API Options
[DEBUG] 26:35.403 RestAPI - create Rest API instance
[DEBUG] 26:35.403 RestAPI - configure Rest API
[DEBUG] 26:35.402 Amplify - amplify config
[DEBUG] 26:35.402 Amplify - component registered in amplify
[DEBUG] 26:35.402 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.402 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.402 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.402 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.401 AnalyticsClass - on hub capsule auth The Auth category has been configured successfully
[DEBUG] 26:35.401 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.401 Hub - Dispatching to auth with The Auth category has been configured successfully
[DEBUG] 26:35.401 Parser - parse config
[DEBUG] 26:35.401 AuthClass - configure Auth
[DEBUG] 26:35.400 Amplify - component registered in amplify
[DEBUG] 26:35.400 RestClient - API Options
[DEBUG] 26:35.400 GraphQLAPI - create Rest instance
[DEBUG] 26:35.400 GraphQLAPI - configure GraphQL API
[DEBUG] 26:35.400 RestClient - API Options
[DEBUG] 26:35.400 RestAPI - create Rest API instance
[DEBUG] 26:35.399 RestAPI - configure Rest API
[DEBUG] 26:35.397 Amplify - component registered in amplify
[DEBUG] 26:35.397 API - API Options
[DEBUG] 26:35.397 GraphQLAPI - API Options
[DEBUG] 26:35.397 RestAPI - API Options
[DEBUG] 26:35.397 Amplify - component registered in amplify
[ERROR] 26:10.350 AuthClass - No current user

Is this helpfull? Anything else I can do to help the investigation if this issue?

chrisbonifacio commented 2 years ago

@vdhpieter it looks like the Auth Class is being configured multiple times, which can result in unpredictable/undesired behavior. Can you check for multiple/duplicate versions of the core or auth amplify packages by running one of the commands from this troubleshooting page in your terminal?

If that doesn't output any packages, then I would check your code for any instances where Amplify or the Auth class might be configured more than once.

if there are duplicate packages in the output, you can try running yarn upgrade --latest --pattern aws-amplify and then check for duplicate dependencies again.

vdhpieter commented 2 years ago

@chrisbonifacio thanks for the response!

When running the troubleshoot command I get this:

@aws-amplify/ui
@aws-amplify/ui-components

Amplify.configure is only called once in the _app file of our next app. Auth.configure is never called...

chrisbonifacio commented 2 years ago

@vdhpieter so those dependencies are duplicated. Did you run one of the upgrade commands and check if those duplicates are still output?

Otherwise, can you share the contents of your package.json?

vdhpieter commented 2 years ago

@chrisbonifacio Yes the duplicates are still there.

Here is the relevant part of my package.json:

{
  ...
  "dependencies": {
    ...
    "@aws-amplify/auth": "^4.3.20",
    "@aws-amplify/core": "^4.3.12",
    "@aws-amplify/ui-components": "^1.9.6",
    "@aws-amplify/ui-react": "^2.1.8",
    ...
    "aws-amplify": "^4.3.12",
}

I also run some other commands to help trouble shooting:

$ npm why @aws-amplify/ui

@aws-amplify/ui@2.0.5
node_modules/@aws-amplify/ui
  @aws-amplify/ui@"2.0.5" from aws-amplify@4.3.12
  node_modules/aws-amplify
    aws-amplify@"^4.3.12" from the root project
    peer aws-amplify@"3.x.x || 4.x.x" from @aws-amplify/ui-components@1.9.6
    node_modules/@aws-amplify/ui-components
      @aws-amplify/ui-components@"^1.9.6" from the root project
    peer aws-amplify@"3.x.x || 4.x.x" from @aws-amplify/ui-react@2.1.8
    node_modules/@aws-amplify/ui-react
      @aws-amplify/ui-react@"^2.1.8" from the root project
    peer aws-amplify@"3.x.x || 4.x.x" from @aws-amplify/ui@3.0.7
    node_modules/@aws-amplify/ui-react/node_modules/@aws-amplify/ui
      @aws-amplify/ui@"3.0.7" from @aws-amplify/ui-react@2.1.8
      node_modules/@aws-amplify/ui-react
        @aws-amplify/ui-react@"^2.1.8" from the root project
    peer aws-amplify@"3.x.x || 4.x.x" from @aws-amplify/ui-components@1.7.2
    node_modules/@aws-amplify/ui-react-v1/node_modules/@aws-amplify/ui-components
      @aws-amplify/ui-components@"1.7.2" from @aws-amplify/ui-react-v1@1.2.9
      node_modules/@aws-amplify/ui-react-v1
        @aws-amplify/ui-react-v1@"npm:@aws-amplify/ui-react@1.2.9" from @aws-amplify/ui-react@2.1.8
        node_modules/@aws-amplify/ui-react
          @aws-amplify/ui-react@"^2.1.8" from the root project

@aws-amplify/ui@3.0.7
node_modules/@aws-amplify/ui-react/node_modules/@aws-amplify/ui
  @aws-amplify/ui@"3.0.7" from @aws-amplify/ui-react@2.1.8
  node_modules/@aws-amplify/ui-react
    @aws-amplify/ui-react@"^2.1.8" from the root project
$ npm why @aws-amplify/ui-components

@aws-amplify/ui-components@1.9.6
node_modules/@aws-amplify/ui-components
  @aws-amplify/ui-components@"^1.9.6" from the root project

@aws-amplify/ui-components@1.7.2
node_modules/@aws-amplify/ui-react-v1/node_modules/@aws-amplify/ui-components
  @aws-amplify/ui-components@"1.7.2" from @aws-amplify/ui-react-v1@1.2.9
  node_modules/@aws-amplify/ui-react-v1
    @aws-amplify/ui-react-v1@"npm:@aws-amplify/ui-react@1.2.9" from @aws-amplify/ui-react@2.1.8
    node_modules/@aws-amplify/ui-react
      @aws-amplify/ui-react@"^2.1.8" from the root project

The reason I also depend on @aws-amplify/ui-components is for the AuthState type which is not exported from somewhere else AFAIK. If that type is included in other packages that could maybe help.

chrisbonifacio commented 2 years ago

Hi @vdhpieter apologies for the delay. If you still have duplicate packages after upgrading, it should be safe to remove the scoped packages like @aws-amplify/auth and @aws-amplify/core. Especially because you already have aws-amplify installed, which includes both of those. The auth scope package is dependent on the core scoped package, so there would be issues there as well.

We basically just want to make sure that there is only one instance of Amplify that gets initialized and configured, that should ensure that only one instance of each module is also initialized. Otherwise, you will end up with two or more instances of Auth which can result in duplicate events/requests and that can lead to errors like "Auth.js throws "Pending sign-in attempt already in progress", for example.

So, please try removing those and only using aws-amplify. You will still be able to import the scoped Amplify packages on with only this package installed. You should still even be able to import the AuthState type from @aws-amplify/ui-components without only aws-amplify installed as well. If you look in your node_modules folder you should be able to see there is still a @aws-amplify folder containing all those scoped packages.

Let me know if that helps or if you are still in need of assistance.

vdhpieter commented 2 years ago

@chrisbonifacio I think you wanted to tag me. I'm able the delete @aws-amplify/auth & @aws-amplify/core. When i delete @aws-amplify/ui-components & @aws-amplify/ui-react they actually disappear.

Secondly it seems like a bad pattern to rely on dependencies of other packages, we even have a linter rule to disallow this...

When removing the core and the auth package I still have the same duplicates...

chrisbonifacio commented 2 years ago

@vdhpieter sorry, I should've mentioned you can also keep the @aws-amplify/ui-react package, that's been moved to its own repository separate from our core js libraries. Also, if you would prefer to keep the scoped packages that's okay, just need to make sure that they're all up to date and compatible so they're not producing duplicate instances.

Are you also trying to get a user's id/access token similarly to the code snippet shared in this issue's description? Or are you running into it in a different context?

const data = (await Auth.currentSession()).getIdToken();
const token = data.getJwtToken();

If you are, can you check your local storage to make sure that the type of token you're trying to get is being stored there after authentication?

vdhpieter commented 2 years ago

@chrisbonifacio we're indeed trying to access the token in the similar way, and I see multiple tokens stored in the local storage

chrisbonifacio commented 2 years ago

@vdhpieter okay, that's good. Would you mind sharing some more context such as a code snippet around how/when you're trying to get the token as well as how you're importing and configuring Amplify in your project?

vdhpieter commented 2 years ago

We have a class for containing logic for the auth strategy. In that class we have this method:

  public async getToken(context: GetServerSidePropsContext) {
    return (await this.getAuth(context)?.currentSession())
      ?.getIdToken()
      .getJwtToken();
  }

We call that method every time we need a token to make an API call (in hooks, in a HOC...)

Normally we only call this if we have a user (we check that with this method)

public async getCurrentUser(
    context?: GetServerSidePropsContext
  ): Promise<ICurrentUser | null> {
    const currentUser = await this.getAuth(context)?.currentUserInfo();

    if (!currentUser) {
      return null;
    }

    return {
      ...currentUser,
      userId: currentUser.attributes['custom:user_id'],
    };
  }

If a page is only visible for authenticated users we use an HOC with this logic to redirect to login:

  const config = getPublicConfig();
    const authStrategy = getAuthStrategy();

    const currentUser = await authStrategy.getCurrentUser(context);

    if (!currentUser) {
      const destination = `/login?redirect=${context.resolvedUrl}`;

      return {
        redirect: {
          destination: destination,
          permanent: false,
        },
      };
    }

Amplify is configured once in our Top Component, here is the code for that call


import { Amplify } from 'aws-amplify';
import urlJoin from 'url-join';

import { getPublicConfig } from '@aaqua-web/config';
import { getIsomorphicWindow } from '@aaqua-web/dom';

let isConfigured = false;

export const configureAmplify = () => {
  const config = getPublicConfig();

  if (isConfigured || config?.authStrategy !== 'cognito') {
    return;
  }

  const window = getIsomorphicWindow();
  const signinUrl = window
    ? urlJoin(window.location.origin, config.basePath, 'login')
    : '';

  Amplify.configure({
    ...config?.amplify,
    oauth: {
      redirectSignIn: signinUrl,
      redirectSignOut: signinUrl,
      ...config.amplify?.oauth,
    },
    ssr: true,
  });

  isConfigured = true;
};```
chrisbonifacio commented 2 years ago

@vdhpieter Looks like you're trying to use the Auth library in a Next application and on the server side. In your scenario, I think you should be using withSSRContext to initialize an Auth instance using the context from the request similar to this:

export const getServerSideProps = async ({ req }) => {
  const { Auth } = withSSRContext({ req });

  let user;

  try {
    user = await Auth.currentAuthenticatedUser();

    return {
      props: {
        user: JSON.stringify(user),
        error: null,
      },
    };
  } catch (error) {
    return {
      props: {
        user: null,
        error: JSON.stringify(error),
      },
    };
  }
};

Note: I'm using a try/catch in my server code when checking for user info because if the "No current user" error is thrown from the server, it will page will prevent the page from loading.

For more information: https://docs.amplify.aws/lib/ssr/q/platform/js/#withssrcontext

Also worth noting - Amplify must load on the client at least once in order to detect and store in either local storage or cookie whether a user is authenticated or not. Otherwise, you're probably going to get the "No current user" error.

See this comment: https://github.com/aws-amplify/amplify-js/issues/8011#issuecomment-839191759 and the one right after offer some more insight on how/when to handle authentication either through _app.js or separate pages.

giulioambrogi commented 2 years ago

+1, suddenly facing this problem in Prod, where I haven't touched anything in ages, I wonder if sth changed in the way the aws token is stored in the browser

chrisbonifacio commented 2 years ago

@giulioambrogi Are you using React Native or Next.js? Some developers are seeing this in an SSR Next.js app, which could be caused by duplicate package versions after upgrading an amplify package (see https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js/)

Could an issue with credentials being sent or not to the server request and/or use of withSSRContext. In React Native, could be an issue with AsyncStorage, etc.

Haven't head back from the original poster of this issue, so I'm going to close this issue. Please open a new issue with your env information, amplify configuration, and code snippet of where the error is occurring for context. This error could happen for multiple reasons and probably isn't the same for everyone.

Harsh2110mishra commented 1 year ago

I am getting same issue i.e "No current user" after confirm sign up if I try to fetch JWT token from Auth in react native

code:

     await Auth.confirmSignUp(username, code);

      const token = (await Auth.currentSession())
        .getAccessToken()
        .getJwtToken();

This throws an error "No current user" sometimes.

tannerabread commented 1 year ago

@Harsh2110mishra from the code snippet you provided you are not signing in to the app but rather verifying that the user is signing up with MFA enabled

You would need to additionally enable auto sign-in in the initial signUp method image

Then you could listen for the autoSignIn or autoSignIn_failure Hub events as shown here to verify if your setup is working correctly

rmazzine commented 5 months ago

Maybe this can be helpful, with Amplify 6 I needed to change a couple of settings to make it work properly:

https://stackoverflow.com/questions/64140993/unauthorized-error-when-using-aws-amplify-with-grahql-to-create-a-new-user/78278864#78278864

When using Amplify 6, there are several possible issues to be solved when facing this problem.

(1)

First, if your data is accessible via role inheritance (i.e. { allow: groups, groups: ["Admin"] } or similar) you should consider setting your appsync auth type in src/amplifyconfiguration.json to: "aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS" instead of "aws_appsync_authenticationType": "API_KEY".

(2)

Then, you may face an issue related to No current user. This is the second step related to your cognito identity pool not having the necessary authorizations. Then, you may need to modify the IAM rule from your service authRole. Then, you need to go to IAM -> Roles -> amplify--authRole and click the tab Tust relationshipsand authorize your user pool with something like:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "cognito-identity.amazonaws.com:aud": "<YOUR_IDENTITY_POOL_ID>"
                },
                "ForAnyValue:StringLike": {
                    "cognito-identity.amazonaws.com:amr": "authenticated"
                }
            }
        }
    ]
}

Where you must replace with the Identity pool ID that can be found in Amazon Cognito -> Identity pools.

(3)

After that, believe or not, you still may face an issue of the type UnauthorizedException, this may happen because your AWS AppSync service related to Auth does not have the right Additional authorization mode. Then you must go to AWS AppSync -> Settings (of your AppSync API) and then to Additional authorization modes and add your respective Amazon Cognito User Pool with the right Authorization mode identifier.

Finally, you may be able to communicate with your graphql CLI!

umerfarok commented 5 months ago
image

i have configured amplify this way and able to fix the problem

mattiLeBlanc commented 1 month ago

@chrisbonifacio I am also seeing this error Runtime error running query logMusicStream. Authmode Cognito. Error: NoSignedUser: No current user when doing a graphql query. Mind you that is works fine for me but one of our customers is triggering this error and I see it in my error logging.

I was reading the comments about duplicate packages, and I am using "aws-amplify": "^6.4.3", and I also had "@aws-amplify/core": "^6.3.1". I now removed this core package but during build of my angular app I am getting an error:

✘ [ERROR] Could not resolve "@aws-amplify/core/internals/utils"

    ../../node_modules/.pnpm/@aws-amplify+api@6.0.42_@aws-amplify+core@6.3.7/node_modules/@aws-amplify/api/dist/esm/index.mjs:4:25:
      4 │ export { ApiError } from '@aws-amplify/core/internals/utils';
        ╵                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  You can mark the path "@aws-amplify/core/internals/utils" as external to exclude it from the bundle, which will remove this error and leave the unresolved path in the bundle.

I think I got this error before and that is why I added the core module. Is probably is because I use PNPM. I really getting a bit annoyed with PNPM and probably move away from it.