Amplify-js: Sessions aren't persisting between app reloads in React Native

Created on 6 Nov 2019  ·  69Comments  ·  Source: aws-amplify/amplify-js

Describe the bug
Sessions aren't persisting between app reloads in Expo

To Reproduce
Steps to reproduce the behavior:

  1. Open the app
  2. Sign in
  3. Reload the app
  4. See error

Expected behavior
User still signed in

Sample code

````
import React, { useState, useEffect } from 'react';
import Amplify from 'aws-amplify';
import Auth from '@aws-amplify/auth'
import awsmobile from './aws-exports';
import { withAuthenticator } from 'aws-amplify-react-native';
import { Text } from 'react-native-elements';

const Test = () => console.log("OK OK OK HERE") || Hi

const TestWithAuth = withAuthenticator(Test)

Amplify.configure(awsmobile);

const App = () => {
useEffect(() => {
Auth.currentAuthenticatedUser()
.then(cognitoUser => console.log(cognitoUser))
.catch(err => console.log(err) || console.log(null))
}, []);

return (

);
}

export default App
````

Core React Native question

Most helpful comment

@bthomas16 i used http://www.typescriptlang.org/play/ to get the JS because I'm lazy and wanted to move on with the build :p

Here is the transpiled (if that is the correct term between TS and JS??):

import AsyncStorage from '@react-native-community/async-storage';
/*
 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
 */
const MEMORY_KEY_PREFIX = '@StorageService:';
let dataMemory = {};
/** @class */
export class MemoryStorageNew {
  /**
   * This is used to set a specific item in storage
   * @param {string} key - the key for the item
   * @param {object} value - the value
   * @returns {string} value that was set
   */
  static setItem(key, value) {
    AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value);
    dataMemory[key] = value;
    return dataMemory[key];
  }
  /**
   * This is used to get a specific key from storage
   * @param {string} key - the key for the item
   * This is used to clear the storage
   * @returns {string} the data item
   */
  static getItem(key) {
    return Object.prototype.hasOwnProperty.call(dataMemory, key)
      ? dataMemory[key]
      : undefined;
  }
  /**
   * This is used to remove an item from storage
   * @param {string} key - the key being set
   * @returns {string} value - value that was deleted
   */
  static removeItem(key) {
    AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key);
    return delete dataMemory[key];
  }
  /**
   * This is used to clear the storage
   * @returns {string} nothing
   */
  static clear() {
    dataMemory = {};
    return dataMemory;
  }
  /**
   * Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage
   * @returns {void}
   */
  static sync() {
    if (!MemoryStorageNew.syncPromise) {
      MemoryStorageNew.syncPromise = new Promise((res, rej) => {
        AsyncStorage.getAllKeys((errKeys, keys) => {
          if (errKeys) rej(errKeys);
          const memoryKeys = keys.filter(key =>
            key.startsWith(MEMORY_KEY_PREFIX),
          );
          AsyncStorage.multiGet(memoryKeys, (err, stores) => {
            if (err) rej(err);
            stores.map((result, index, store) => {
              const key = store[index][0];
              const value = store[index][1];
              const memoryKey = key.replace(MEMORY_KEY_PREFIX, '');
              dataMemory[memoryKey] = value;
            });
            res();
          });
        });
      });
    }
    return MemoryStorageNew.syncPromise;
  }
}
MemoryStorageNew.syncPromise = null;
/** @class */
export default class StorageHelper {
  /**
   * This is used to get a storage object
   * @returns {object} the storage
   */
  constructor() {
    this.storageWindow = MemoryStorageNew;
  }
  /**
   * This is used to return the storage
   * @returns {object} the storage
   */
  getStorage() {
    return this.storageWindow;
  }
}

I've actually got a branch on my project to move over to TS now - but for the MVP we're sticking with JS. That's gonna be the mother of all PR's......

Also thanks @district-michael and @erlix322 :) I mistagged before

All 69 comments

I have been seeing the exact same issue. Glad to see this bug is being filed. Using Expo + React Native, I thought I had messed up in my soon to be production codebase. So I just created a new, basic, bare-bones application using Expo + React Native + Amplify (Cognito) and still cannot persist state when refreshing the application

APP.JS

import React from 'react';
import { StyleSheet, Text, View, AsyncStorage } from 'react-native';
import Amplify, {Auth, Analytics} from 'aws-amplify';
import aws_exports from './aws-exports';
import { withAuthenticator } from 'aws-amplify-react-native'

Amplify.configure(aws_exports);
Analytics.disable()

class App extends React.Component {
  render() {
    return (
        <View style={styles.container}>
          <Text>Open up App.js to start working on your app!</Text>
        </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default  withAuthenticator(App);

AWS-EXPORTS

// 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:xxxxxxcxcxcxcxcxcxcxcx",
    "aws_cognito_region": "us-east-2",
    "aws_user_pools_id": "us-east-x_xxxxxxxxxx",
    "aws_user_pools_web_client_id": "7rh4ap4nxxxxxxxxxxxxx",
    "oauth": {}
};

export default awsmobile;

I was having this myself and was tearing my hair out trying to figure it out. I discovered that the current amplify sdk is using the old version of async-storage from before they broke it out into being a react-native community package. When I inspected what was in the async-storage, I found the tokens would intermittently disappear, which would cause my session to break sometimes. I implemented a replacement storage service and passed that into my Amplify.configure Auth object. Note that I'm explicitly importing the react-native-community/async-storage package in the StorageService. Code below:

```StorageService.ts

import AsyncStorage from '@react-native-community/async-storage'

/*

  • Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
    *
  • Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
  • the License. A copy of the License is located at
    *
  • http://aws.amazon.com/apache2.0/
    *
  • or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  • CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
  • and limitations under the License.
    */

const MEMORY_KEY_PREFIX = '@StorageService:'
let dataMemory: any = {}

/* @class */
export class MemoryStorageNew {
static syncPromise: Promise | null = null
/
*

  • This is used to set a specific item in storage
  • @param {string} key - the key for the item
  • @param {object} value - the value
  • @returns {string} value that was set
    */
    static setItem(key: any, value: any) {
    AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value)
    dataMemory[key] = value
    return dataMemory[key]
    }

/**

  • This is used to get a specific key from storage
  • @param {string} key - the key for the item
  • This is used to clear the storage
  • @returns {string} the data item
    */
    static getItem(key: string) {
    return Object.prototype.hasOwnProperty.call(dataMemory, key)
    ? dataMemory[key]
    : undefined
    }

/**

  • This is used to remove an item from storage
  • @param {string} key - the key being set
  • @returns {string} value - value that was deleted
    */
    static removeItem(key: string) {
    AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key)
    return delete dataMemory[key]
    }

/**

  • This is used to clear the storage
  • @returns {string} nothing
    */
    static clear() {
    dataMemory = {}
    return dataMemory
    }

/**

  • Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage
  • @returns {void}
    */
    static sync() {
    if (!MemoryStorageNew.syncPromise) {
    MemoryStorageNew.syncPromise = new Promise((res, rej) => {
    AsyncStorage.getAllKeys((errKeys, keys) => {
    if (errKeys) rej(errKeys)
    const memoryKeys = keys!.filter(key =>
    key.startsWith(MEMORY_KEY_PREFIX)
    )
    AsyncStorage.multiGet(memoryKeys, (err, stores) => {
    if (err) rej(err)
    stores!.map((result, index, store) => {
    const key = store[index][0]
    const value = store[index][1]
    const memoryKey = key.replace(MEMORY_KEY_PREFIX, '')
    dataMemory[memoryKey] = value
    })
    res()
    })
    })
    })
    }
    return MemoryStorageNew.syncPromise
    }
    }

/* @class */
export default class StorageHelper {
private storageWindow: any
/
*

  • This is used to get a storage object
  • @returns {object} the storage
    */
    constructor() {
    this.storageWindow = MemoryStorageNew
    }

/**

  • This is used to return the storage
  • @returns {object} the storage
    */
    getStorage() {
    return this.storageWindow
    }
    }
    ```

```AmplifyService.ts
import { MemoryStorageNew } from './StorageService'
Amplify.configure({
Auth: {
...
storage: MemoryStorageNew,
},
})
````

I will definitely try this shortly and update with my progress. But this seems like extra steps (granted, temporarily) that shouldn't be needed for an otherwise "out of the box" solution to Auth. Either way, thanks for doing the deep dive that was in my near future :).

A fallback solution seems to be to rollback to the last version of Amplify before this bug was introduced

I will definitely try this shortly and update with my progress. But this seems like extra steps (granted, temporarily) that shouldn't be needed for an otherwise "out of the box" solution to Auth. Either way, thanks for doing the deep dive that was in my near future :).

A fallback solution seems to be to rollback to the last version of Amplify before this bug was introduced

which version of amplify is using the working storage? I'll most likely downgrade because I use expo and will not link the community storage

EDIT

For those who are using Expo and don't want to eject for now it is enough to apply the solution from @district-michael above and replace the line:

import AsyncStorage from '@react-native-community/async-storage'

with

import {AsyncStorage} from 'react-native'

and override your Configuration

Amplify.configure({
  Auth:{
    region: ...,    
    userPoolId: ...,
    userPoolWebClientId: ...,
    storage: MemoryStorageNew
  }
});

@bthomas16 thank you so much for this patch - saved me from going insane, I thought I'd broken my build...

For all those interested, @district-michael is the hero here (along with @Erlix322). That said, I tried modifying his solution to fit vanilla Javascript implementations, this proved difficult and not worth the effort. And after creating a new bare-bones applications with Typescript, Michael's solution worked like a charm. Typescript is becoming a best practice anyways, so I am choosing to see this as a positive for my project's future development

@bthomas16 i used http://www.typescriptlang.org/play/ to get the JS because I'm lazy and wanted to move on with the build :p

Here is the transpiled (if that is the correct term between TS and JS??):

import AsyncStorage from '@react-native-community/async-storage';
/*
 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
 */
const MEMORY_KEY_PREFIX = '@StorageService:';
let dataMemory = {};
/** @class */
export class MemoryStorageNew {
  /**
   * This is used to set a specific item in storage
   * @param {string} key - the key for the item
   * @param {object} value - the value
   * @returns {string} value that was set
   */
  static setItem(key, value) {
    AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value);
    dataMemory[key] = value;
    return dataMemory[key];
  }
  /**
   * This is used to get a specific key from storage
   * @param {string} key - the key for the item
   * This is used to clear the storage
   * @returns {string} the data item
   */
  static getItem(key) {
    return Object.prototype.hasOwnProperty.call(dataMemory, key)
      ? dataMemory[key]
      : undefined;
  }
  /**
   * This is used to remove an item from storage
   * @param {string} key - the key being set
   * @returns {string} value - value that was deleted
   */
  static removeItem(key) {
    AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key);
    return delete dataMemory[key];
  }
  /**
   * This is used to clear the storage
   * @returns {string} nothing
   */
  static clear() {
    dataMemory = {};
    return dataMemory;
  }
  /**
   * Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage
   * @returns {void}
   */
  static sync() {
    if (!MemoryStorageNew.syncPromise) {
      MemoryStorageNew.syncPromise = new Promise((res, rej) => {
        AsyncStorage.getAllKeys((errKeys, keys) => {
          if (errKeys) rej(errKeys);
          const memoryKeys = keys.filter(key =>
            key.startsWith(MEMORY_KEY_PREFIX),
          );
          AsyncStorage.multiGet(memoryKeys, (err, stores) => {
            if (err) rej(err);
            stores.map((result, index, store) => {
              const key = store[index][0];
              const value = store[index][1];
              const memoryKey = key.replace(MEMORY_KEY_PREFIX, '');
              dataMemory[memoryKey] = value;
            });
            res();
          });
        });
      });
    }
    return MemoryStorageNew.syncPromise;
  }
}
MemoryStorageNew.syncPromise = null;
/** @class */
export default class StorageHelper {
  /**
   * This is used to get a storage object
   * @returns {object} the storage
   */
  constructor() {
    this.storageWindow = MemoryStorageNew;
  }
  /**
   * This is used to return the storage
   * @returns {object} the storage
   */
  getStorage() {
    return this.storageWindow;
  }
}

I've actually got a branch on my project to move over to TS now - but for the MVP we're sticking with JS. That's gonna be the mother of all PR's......

Also thanks @district-michael and @erlix322 :) I mistagged before

This did it for me with one minor edit since we're on managed Expo

import { AsyncStorage } from 'react-native';

instead of (which requires linking)

import AsyncStorage from '@react-native-community/async-storage';

Ah true, sorry!


From: Cody Swann notifications@github.com
Sent: Thursday, November 7, 2019 9:53:20 PM
To: aws-amplify/amplify-js amplify-js@noreply.github.com
Cc: Humphreys, Anthony anthony.humphreys@lancaster.ac.uk; Comment comment@noreply.github.com
Subject: [External Sender] Re: [aws-amplify/amplify-js] Sessions aren't persisting between app reloads in React Native (#4351)

This email originated from outside of the University. Do not click links or open attachments unless you recognise the sender and know the content is safe.

This did it for me with one minor edit since we're on managed Expo

import { AsyncStorage } from 'react-native';

instead of (which requires linking)

import AsyncStorage from '@react-native-community/async-storage';


You are receiving this because you commented.
Reply to this email directly, view it on GitHubhttps://eur02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Faws-amplify%2Famplify-js%2Fissues%2F4351%3Femail_source%3Dnotifications%26email_token%3DACP2QUX2LJIY2HPUQKCGDLTQSSE5BA5CNFSM4JJNMPP2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEDN6RRI%23issuecomment-551282885&data=02%7C01%7Canthony.humphreys%40lancaster.ac.uk%7C384ad2188fad4a7b5a2d08d763cce97d%7C9c9bcd11977a4e9ca9a0bc734090164a%7C1%7C0%7C637087604052185062&sdata=88vQvvuF1zrXn6TTdtbDH1LH5pr31KryWXRZzj55enU%3D&reserved=0, or unsubscribehttps://eur02.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FACP2QUVU3ZQVCCWEXKVTX5TQSSE5BANCNFSM4JJNMPPQ&data=02%7C01%7Canthony.humphreys%40lancaster.ac.uk%7C384ad2188fad4a7b5a2d08d763cce97d%7C9c9bcd11977a4e9ca9a0bc734090164a%7C1%7C0%7C637087604052185062&sdata=q6I84ltRiqxPARPeSXVVm4Skl7vWoUB5zkBirLccEks%3D&reserved=0.

Now that we have a workaround... great. But what actually happened to cause this and when will we be able to rely on Amplify without this work around?

We are Facing same issue.Here is the Steps that i found the issue with React-native amplify library.

1.) WORKING FLOW:

  • start the app, login successfully.
  • move to change password screen, call the Method `Auth.currentAuthenticatedUser().
  • able to get the required data

2.) FLOW WITH ISSUE:

  • After SignIn restart the app without signOut
  • Auth.currentAuthenticatedUser() didn't return the required data. the same flow is working in WebApp(i.e. React).

After Reloading the App the Session is not maintained. Also Auth.currentSession() is also returns null value.

3.)EXPECTED BEHAVIOUR

  • After Auth.signIn() the User Should get required data in Auth.currentAuthenticatedUser()(also if user reload the app) until user calls Auth.signOut() .

Thank you @district-michael and @Erlix322 for the solutions, worked for me. If you have federated providers (like Facebook and Google) you additionally need to do the following:

const refreshToken = async () => {
    await MemoryStorageNew.sync();
    const federatedInfo = MemoryStorageNew.getItem("aws-amplify-federatedInfo");
    const federatedInfoParsed = JSON.parse(federatedInfo);
    const { token } = federatedInfoParsed;

    return {
        token,
    };
};

and then in your configure:

Auth.configure({
        refreshHandlers: {
            google: refreshToken,
            facebook: refreshToken
        },
        storage: MemoryStorageNew
    });

Hi,

I initially thought that the issue here would be related to Async Storage deprecation, and opened the PR #4402 to migrate to the community version. However after looking at the issue description and comments, it seems the issue occurs on Expo as well, where RN is still <0.60.
Also the workaround suggested by @Erlix322 and @CodySwannGT for managed Expo still uses Async storage.

Additionally even in the case of stand alone React Native apps as mentioned in this comment, the issue was not observed on even 0.61.4 with a previous version of Amplify. So it seems to me the issue might be with some commit in the last 1 month, rather than Async Storage deprecation? (it is still part of RN but would be removed soon)

We are still investigating the cause but let us know if that makes sense. Would appreciate your insights and suggestions.

Additionally if we switch to the community edition of Async Storage, it seems to break managed expo users as they will need to eject to use the native module until Expo themselves includes it. Here is a thread related to that. Expo users let us know your thoughts on us switching to the community version and ejecting your app, or using previous versions of Amplify until Expo supports it for managed apps.

As improved ejected expo is, we still avoid it at all cost, so we would vote very strongly against forcing us to eject.

Most likely expo will include it in the SDK. Seems to be in progress as well. https://expo.canny.io/feature-requests/p/continued-support-for-asyncstorage

@Ashish5591

The Auth package uses StorageHelper().getStorage() to determine where to store the user data.

For web, it's supposed to use window.localStorage or, failing that, in-memory storage.
For react native, it's supposed to use AsyncStorage.

There was an issue in core/package.json that prevented the correct react native versions of ClientDevice (this affects Analytics and Push Notifications), RNComponents, and StorageHelper from being used correctly.

You can test this with the code

  useEffect(() => {
    AsyncStorage.clear();
    const storage = new StorageHelper().getStorage();
    storage.setItem('test1', 'test2');
    console.log('storage.getItem(test1) = ', storage.getItem('test1'));
    AsyncStorage.getAllKeys().then(async keys => {
      console.log('AsyncStorage.getAllKeys = ', keys);
    });
  }, []);

In the aws-amplify@latest (1.2.4), the result is

 LOG  storage.getItem(test1) =  test2
 LOG  AsyncStorage.getAllKeys =  []

In aws-amplify@next (2.1.0), the result is

 LOG  storage.getItem(test1) =  test2
 LOG  AsyncStorage.getAllKeys =  ["@MemoryStorage:test1"]

The reason the workaround of creating a MemoryStorage class to be passed into the Auth config worked, is that it basically manually replaced the incorrect web version of StorageHelper with a copy of the react native version.

@dantasfiles Thanks for your detailed response!

Looking into that further, the fix for the react native source files not being included made it into our master branch but seems to not have been included in a new 1.x.x release.

It went straight to 2.x.x which needs to be installed through aws-amplify@next as you said and people using @latest would not have picked up the change.

Installing aws-amplify@next should resolve the issue:

npm install aws-amplify@next

That said we will also do a release to @latest with the fix early next week.

@Ashish-Nanda did this fix make it into a release to @latest yet? I checked in the PRs and releases but honestly couldn't find much in the amount of them.

@dantasfiles Thanks for your detailed response!

Looking into that further, the fix for the react native source files not being included made it into our master branch but seems to not have been included in a new 1.x.x release.

It went straight to 2.x.x which needs to be installed through aws-amplify@next as you said and people using @latest would not have picked up the change.

Installing aws-amplify@next should resolve the issue:

npm install aws-amplify@next

That said we will also do a release to @latest with the fix early next week.

I've just updated to the newest release of 2.2.0 and still experiencing the same issue - refreshing the projct clears the cognito user from the storage.

Tested now, still not working. Please fix.

Hi @gvankeerberghen the fix is in @latest.

@KristineTrona and @ajdinahmetovic I just tested with 2.2.0 and it worked fine as far as I can tell. This was with a standalone RN app created through the RN cli and not expo. RN version is 0.61.4

Could you tell me more about your setup? Are you using expo or stand alone RN and what is in your package.json?

Looking at this comment it seems 2.1.0 was working for other users as well.

If any other users have tried @latest please let us know if the issue is resolved for you.

@Ashish-Nanda My setup is exactly the same and after testing again - it is indeed fixed. :) Perhaps I hadn't rebuilt the project since the aws-amplify update.

@KristineTrona Thanks for the validation!

@ajdinahmetovic Can you do another upgrade to @latest & let us know if it's been resolved for you and, if not, more about your reproduction steps?

@ericclemmons Hey, after upgrade it works for me. Thank you 🙂

Thanks for confirming that the fix works for you. Since the problem is resolved I'm going to go ahead and close out this issue.

@KristineTrona - How did you finally get it to work? I've updated to 2.2.0, deleted node_modules, did a fresh pod install etc. etc. and I am still seeing the issue. Thanks!

@KristineTrona - How did you finally get it to work? I've updated to 2.2.0, deleted node_modules, did a fresh pod install etc. etc. and I am still seeing the issue. Thanks!

If using yarn -- did you delete the yarn.lock file?

I tried deleting package-lock.json and made no difference

@markmckim What does npm view aws-amplify return for you?


[email protected] | MIT | deps: none | versions: 11
Amplify is a wrapper around the NodeJS http packages to help make development easier.

dist
.tarball: https://registry.npmjs.org/amplify/-/amplify-0.0.11.tgz
.shasum: fd81c7068c862823f2508b8f3c650eb76753f58c

maintainers:
- chafnan <[email protected]>

dist-tags:
latest: 0.0.11  

published over a year ago by chafnan <[email protected]>

Although this seems weird? My package.json has 2.2.0

That's weird. Did you run npm view aws-amplify or npm view amplify?

The amplify package is owned by someone else: https://github.com/chafnan/amplify

(I've made this mistake a lot 😉)

In fact, a better command would be:

npx envinfo --system --binaries --browsers --npmPackages --npmGlobalPackages

Run that and copy/paste what you get back, which should help 🤞

Whoops! My bad. When I run that against the proper package this time 😀 then I get this...


{\rtf1\ansi\ansicpg1252\cocoartf2511
\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fnil\fcharset0 Menlo-Bold;\f1\fnil\fcharset0 Menlo-Regular;}
{\colortbl;\red255\green255\blue255;\red57\green192\blue38;\red0\green0\blue0;\red56\green185\blue199;
\red170\green171\blue37;}
{\*\expandedcolortbl;;\cssrgb\c25704\c77963\c19556;\csgray\c0;\cssrgb\c25544\c77008\c82022;
\cssrgb\c72330\c71683\c18597;}
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\pardirnatural\partightenfactor0

\f0\b\fs22 \cf2 \ul \ulc2 \CocoaLigature0 aws-amplify\cf3 \ulc3 @\cf2 \ulc2 2.2.0
\f1\b0 \cf3 \ulnone  | \cf2 Apache-2.0\cf3  | deps: \cf4 11\cf3  | versions: \cf5 542\cf3 \
AWS Amplify is a JavaScript library for Frontend and mobile developers building cloud-enabled applications.\
\cf4 https://aws-amplify.github.io/\cf3 \
\
dist\
.tarball: \cf4 https://registry.npmjs.org/aws-amplify/-/aws-amplify-2.2.0.tgz\cf3 \
.shasum: \cf5 10560dd838f2d7b9f5d21622cb6c9c723dcbbeb3\cf3 \
.integrity: \cf5 sha512-3eG/qRzl29y4Ro5PHZrmzRB64eg0+/xYU9w1Kb3iJG8CdMux3W5+1fQnfjKOFSSImlUdgDos2Wlrm243NRb+Nw==\cf3 \
.unpackedSize: \cf5 8.5\cf3  MB\
\
dependencies:\
\cf5 @aws-amplify/analytics\cf3 : ^2.2.0    \cf5 @aws-amplify/predictions\cf3 : ^2.1.1  \
\cf5 @aws-amplify/api\cf3 : ^2.1.1          \cf5 @aws-amplify/pubsub\cf3 : ^2.1.1       \
\cf5 @aws-amplify/auth\cf3 : ^2.1.1         \cf5 @aws-amplify/storage\cf3 : ^2.1.1      \
\cf5 @aws-amplify/cache\cf3 : ^2.1.1        \cf5 @aws-amplify/ui\cf3 : ^1.1.3           \
\cf5 @aws-amplify/core\cf3 : ^2.2.0         \cf5 @aws-amplify/xr\cf3 : ^1.1.1           \
\cf5 @aws-amplify/interactions\cf3 : ^2.1.1 \
\
maintainers:\
- \cf5 amzn-oss\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 aws-amplify-ops\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 elorzafe\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 haverchuck\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 jamesiri\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 jpeddicord\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 kaustavghosh06\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 manuel.iglesias\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 michaelzhou\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 mlabieniec\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 powerful23\cf3  <\cf4 [email protected]\cf3 >\
- \cf5 undefobj\cf3  <\cf4 [email protected]\cf3 >\
\
dist-tags:\

\f0\b \cf2 beta
\f1\b0 \cf3 : 1.1.24-beta.10                  
\f0\b \cf2 preview
\f1\b0 \cf3 : 1.1.31-preview.41            \

\f0\b \cf2 latest
\f1\b0 \cf3 : 2.2.0                         
\f0\b \cf2 rn-hosted-ui
\f1\b0 \cf3 : 1.1.20-rn-hosted-ui2.3  \

\f0\b \cf2 next
\f1\b0 \cf3 : 2.1.0                           
\f0\b \cf2 unstable
\f1\b0 \cf3 : 2.2.1-unstable.5            \
\
published \cf5 a week ago\cf3  by \cf5 aws-amplify-ops\cf3  <\cf4 [email protected]\cf3 >}

Thanks!

Huh! That's the correct version, alright!

Can you help me understand step-by-step what actions your taking to still see this error? Honestly, even starting with the basics (e.g. npm install, npm run-script android, click "Sign In", etc.) will help!

@ericclemmons So I was previously running an older version (can't remember exactly as I'm not at home right now. Say something like 1.x.x) and I was seeing the broken behaviour where app refreshes would lose auth state and I would be returned to my Sign In screen.

After reading the comments above last night, I updated the value in my package.json to 2.2.0, and did an npm install followed by a pod install. This didn't work.

I then tried doing all the following before trying again:

  • Delete package-lock.json
  • Delete node_modules
  • Delete Pods folder
  • Clear React-Native / Watchman cache
  • Deleted Xcode Derived Data
  • Run npm install
  • Run pod install
  • Run npm start
  • Build and run iOS app
  • Issue still persists

Some additional info which may/may not have an impact on this.

  • This is not an Expo or react-native cli generated app
  • It is a custom app in which I integrated React Native manually
  • However everything still works like a normal react-native cli generated app (e.g. I run npm run bundle before creating a release build etc.
  • I am not using withOAuth, I have my own custom auth components (e.g. SignUp, SignIn etc.)
  • When my code calls Auth.currentAuthenticatedUser() after a refresh (or a fresh app launch) - It is no longer Signed In. (From memory, I get a "Not Authenticated" error).

This code was working perfectly for months before upgrading to the broken version a few weeks ago, and all I did then was update the package.json version, so I assumed that once again upgrading the latest version would fix the issue.

It's possible, but I can't see anywhere in my code that would be causing this, since it's just a call to Auth.currentAuthenticatedUser() and it feels like maybe something cached somewhere or a stale version somewhere....but I've tried deleting the app from the device and reinstalling and just can't seem to pin it down. Any help much appreciated!

@markmckim This is extremely helpful!

First, let's try Auth.currentAuthenticatedUser({ bypassCache: true }), which should force a round-trip to Cognito:

https://aws-amplify.github.io/docs/js/authentication#retrieve-current-authenticated-user

However, we're addressing a known bug (race-condition) that exists with Auth.currentAuthenticatedUser where the first attempt returns a _Not Authenticated_ error, but a subsequent call succeeds. This sounds a lot like what you're seeing.

Lastly, try a Hub.listen("auth", ...) call to the section of code where you're calling Auth.currentAuthenticatedUser(), as seen here:

https://aws-amplify.github.io/docs/js/authentication#oauth-and-hosted-ui)

Please report back if the signIn or signOut calls are being called with the user object, or if the bypassCache option works for you. 🙏

Hi there -- been watching this issue for a while and am excited for the progress.

Is there a commit tied to this issue? Couldn't find one mentioned above.

We're using the amazon-cognito-identity-js library, which doesn't seem to have been updated at the same time as aws-amplify... so I'm thinking that our problems probably haven't been addressed quite yet. :-/

@benmgreene Can you share some details on you're use-case with amazon-cognito-identity-js directly vs. the Auth module (linked above)?

You're right, aws-amplify gets the majority of usage & testing, so there could be something specific to amazon-cognito-identity-js & you're use-case that we need to dig into.

@ericclemmons From what I can tell from the Auth module, for React Native apps it seems to rely upon amazon-cognito-identity-js anyhow. One of the major problems we currently have is that the import { AsyncStorage } from 'react-native'; line has not been updated to pull from @react-native-community. Though it may well be that there are other issues contributing to our sporadic session loss that have now been addressed, it's not clear to me what changes those were.

As to what's different in our usage of the Auth vs amazon-cognito-identity-js, I imagine we could and will migrate to Auth at some point, but not without significant investment.

That's interesting @benmgreene ... I have amazon-cognito-identity-js listed in my package.json as instructed here: https://aws-amplify.github.io/docs/js/authentication#configure-your-app

I currently have 3.2.0 of amazon-cognito-identity-js. I wonder could this be related to my issue?

I am however using the Auth module directly in my code, and only including amazon-cognito-identity-js in package.json due to the instructions linked above.

@ericclemmons - Thanks for the help...I'll try your suggested steps now and report back.

@ericclemmons - Ran a few tests...

  • Changing the call to be Auth.currentAuthenticatedUser({ bypassCache: true }) made no difference unfortunately
  • I already had a Hub listening for Auth events and can confirm that no Auth event at all is fired when the app is refreshed (and Auth.currentAuthenticatedUser is called)

Thanks!

@markmckim Ok, we'll need to dig into this more then! I should be able to replicate your scenario by setting up a project via https://aws-amplify.github.io/docs/js/start#option-2-use-react-native-cli-recommended-if-you-have-mobile-development-experience for iOS correct?

I want to ensure I'm following your reproduction steps as close as possible...

Thanks @ericclemmons - This is probably the closest instructions for configuring my iOS app:
https://facebook.github.io/react-native/docs/integration-with-existing-apps

However I imagine that your link would probably be close enough (and quicker).
Also I am using CocoaPods, but again, not sure if that is related.

@markmckim what version of RN are you using? You only need to do pod install for RN 0.60+

Regarding the new version of amplify not being picked up: Maybe the packager cache is using the old version of amplify you had installed.

Could you try the following:
1) Stop packager
2) Delete node modules
3) npm install
4) rm -fr $TMPDIR/metro*
5) npm start --reset-cache (on a different terminal tab/window)
6) npx react-native run-ios

Hopefully that will pick up the version 2.2.0 that you have installed and fix the issue related to sessions not being persisted.

@ericclemmons From what I can tell from the Auth module, for React Native apps it seems to rely upon amazon-cognito-identity-js anyhow. One of the major problems we currently have is that the import { AsyncStorage } from 'react-native'; line has not been updated to pull from @react-native-community. Though it may well be that there are other issues contributing to our sporadic session loss that have now been addressed, it's not clear to me what changes those were.

As to what's different in our usage of the Auth vs amazon-cognito-identity-js, I imagine we could and will migrate to Auth at some point, but not without significant investment.

Hi @benmgreene
This issue is not related to the community version of AsyncStorage not being used. That was what everyone felt initially but we realized that it does not have anything to do with it for reasons explained in this comment

Also the root cause was found out and elaborated on both here and in this comment.

Now we will need to move to the community edition once RN actually removes AsyncStorage from a future version, but we are not going to be doing it till then since it will break Expo users until Expo itself includes the community edition. So we are not doing it beforehand to avoid breaking RN users who use Amplify with Expo and dont want to eject.
Also in this case it does not cause the issue related to sessions not persisting, and the fix has been confirmed by users above.

Could you elaborate more about your issue. Are you only using amazon-cognito-identity-js and not Auth from Amplify?
If your case seems different from most users on this thread, it might be better to file a new issue with details of your setup, the issue itself and which version introduced it for you.

@Ashish-Nanda I tried all of the above steps and it made no difference unfortunately.

I am using React Native 0.61.5 (hence the pod install).

Here is my package.json dependencies list:

"devDependencies": {
    "babel-eslint": "10.0.3",
    "babel-preset-react-native": "5.0.2",
    "eslint": "6.7.2",
    "eslint-config-airbnb": "18.0.1",
    "eslint-config-prettier": "6.7.0",
    "eslint-plugin-import": "2.18.2",
    "eslint-plugin-jest": "23.1.1",
    "eslint-plugin-jsx-a11y": "6.2.3",
    "eslint-plugin-prettier": "3.1.1",
    "eslint-plugin-react": "7.17.0",
    "eslint-plugin-react-native": "3.8.1",
    "jest": "24.9.0",
    "prettier": "1.18.2"
  },
  "dependencies": {
    "@react-native-community/async-storage": "1.6.2",
    "@react-native-community/geolocation": "2.0.2",
    "amazon-cognito-identity-js": "3.2.0",
    "aws-amplify": "2.2.0",
    "native-base": "2.13.8",
    "prop-types": "15.7.2",
    "react": "16.12.0",
    "react-native": "0.61.5",
    "react-native-camera": "3.13.1",
    "react-native-device-info": "5.3.1",
    "react-native-flip-card": "3.5.5",
    "react-native-gesture-handler": "1.5.2",
    "react-native-image-header-scroll-view": "0.10.3",
    "react-native-maps": "0.26.1",
    "react-native-qrcode-svg": "6.0.1",
    "react-native-reanimated": "1.4.0",
    "react-native-sound": "0.11.0",
    "react-native-spinkit": "1.5.0",
    "react-native-svg": "9.13.3",
    "react-native-swiper": "1.6.0-rc.3",
    "react-native-vector-icons": "6.6.0",
    "react-native-webview": "7.6.0",
    "react-navigation": "4.0.10",
    "react-navigation-stack": "1.10.3",
    "react-navigation-tabs": "2.6.2",
    "react-redux": "7.1.3",
    "redux": "4.0.4",
    "redux-devtools-extension": "2.13.8",
    "redux-persist": "6.0.0",
    "redux-thunk": "2.3.0",
    "shortid": "2.2.15"
  }

Hello @Ashish-Nanda
From my side very weird case.

Until yesterday I builded and released many versions with this configuration:
"amazon-cognito-identity-js": "^3.0.15",
"aws-amplify": "^1.1.29",
"react": "16.9.0",
"react-native": "0.61.4",
It worked very well.

Today I faced the issue session wasn't anymore persistent.
So I updated my dependecies to latest
"amazon-cognito-identity-js": "^3.2.0",
"aws-amplify": "^2.2.0",
Issue is gone away and session is again persistent.

Do you know how would it be possible?

Sounds like a few of the folks in this thread are having some issues with dependencies. FWIW, I've added dependabot to my repository and haven't seen any issues since the fix was pushed.

I stile have the same issue, its weird because 2days ago, i thought every was fine,

I tested @latest and @next but the result is the same,

after relstart the application user is disconnected

  Auth.currentSession()
    .then(data => console.log(data))
    .catch(err => console.log(err));

I agree with @mickadoua, I tesed few days ago it was working fine. Now I have same issues again 😕

I tried deleting node_modules, reseting cache, reseting android folder, tried @latest and @next I couldnt manage to get it working now.

in Android I dont have any issue

@mickadoua Can you share package.json and how you use Auth.currentAuthenthicatedUser() ?
Which version of react native are you using ?

@ajdinahmetovic hello and thanks for your help,

I use this code to get the CognitoToken

export async function getCognitoToken(): Promise<string> {
  const cognitoUser = await Auth.currentAuthenticatedUser();
  const currentSession = await Auth.currentSession();
  return await new Promise((resolve, reject) => {
    cognitoUser.refreshSession(
      currentSession.refreshToken,
      (err, session) => {
        if (err) {
          reject(err);
        }
        return resolve(session.idToken.jwtToken);
      },
    );
  });
}


Environment


``` System:
OS: macOS 10.15.2
CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
Memory: 76.56 MB / 16.00 GB
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 12.7.0 - ~/.nvm/versions/node/v12.7.0/bin/node
Yarn: 1.21.1 - ~/code/client/psa/react-native/node_modules/.bin/yarn
npm: 6.10.0 - ~/.nvm/versions/node/v12.7.0/bin/npm
Browsers:
Chrome: 79.0.3945.88
Safari: 13.0.4
npmPackages:
@babel/core: 7.6.2 => 7.6.2
@babel/preset-flow: 7.0.0 => 7.0.0
@babel/register: ^7.6.2 => 7.7.4
@babel/runtime: 7.5.5 => 7.5.5
@bam.tech/react-native-batch: 5.0.2 => 5.0.2
@mapbox/polyline: 1.0.0 => 1.0.0
@react-native-community/async-storage: ^1.7.1 => 1.7.1
@react-native-community/eslint-config: ^0.0.5 => 0.0.5
@react-native-community/geolocation: ^2.0.2 => 2.0.2
@react-native-community/google-signin: ^3.0.3 => 3.0.3
@react-native-community/netinfo: 4.6.1 => 4.6.1
@react-native-community/slider: 2.0.7 => 2.0.7
@react-native-firebase/analytics: ^6.1.0 => 6.2.0
@react-native-firebase/app: ^6.1.0 => 6.2.0
@react-native-firebase/crashlytics: ^6.1.0 => 6.2.0
@react-native-firebase/perf: ^6.1.0 => 6.2.0
add: ^2.0.6 => 2.0.6
amazon-cognito-identity-js: ^3.2.0 => 3.2.0
aws-amplify: ^2.2.0 => 2.2.0
axios: ^0.19.0 => 0.19.0
babel-eslint: 10.0.1 => 10.0.1
babel-jest: 24.9.0 => 24.9.0
babel-plugin-module-resolver: ^3.2.0 => 3.2.0
babel-plugin-transform-inline-environment-variables: 0.4.3 => 0.4.3
babel-plugin-transform-object-rest-spread: 6.26.0 => 6.26.0
babel-plugin-transform-remove-console: 6.9.4 => 6.9.4
babel-runtime: 6.26.0 => 6.26.0
base64-arraybuffer: 0.2.0 => 0.2.0
enzyme: 3.9.0 => 3.9.0
enzyme-adapter-react-16: 1.12.1 => 1.12.1
eslint: 6.5.1 => 6.5.1
eslint-config-airbnb-standard: 3.0.1 => 3.0.1
eslint-config-prettier: 4.1.0 => 4.1.0
eslint-import-resolver-alias: ^1.1.2 => 1.1.2
eslint-plugin-flowtype: 4.2.0 => 4.2.0
eslint-plugin-import: ^2.18.0 => 2.19.1
eslint-plugin-prettier: 3.0.1 => 3.0.1
eslint-plugin-react: 7.12.4 => 7.12.4
eslint-plugin-react-native: 3.6.0 => 3.6.0
eslint-plugin-react-native-a11y: 1.2.0 => 1.2.0
fetch: 1.1.0 => 1.1.0
filequeue: ^0.5.0 => 0.5.0
flow-bin: 0.105.1 => 0.105.1
flow-typed: 2.6.1 => 2.6.1
flowgen: ^1.10.0 => 1.10.0
google-polyline: 1.0.3 => 1.0.3
hoist-non-react-statics: 3.3.0 => 3.3.0
husky: 1.3.1 => 1.3.1
i18n-js: ^3.3.0 => 3.5.0
intl: 1.2.5 => 1.2.5
jest: 24.9.0 => 24.9.0
jest-enzyme: 7.0.2 => 7.0.2
jest-react-native: 18.0.0 => 18.0.0
jest-sonar-reporter: 2.0.0 => 2.0.0
jetifier: ^1.6.4 => 1.6.5
jwt-decode: ^2.2.0 => 2.2.0
libphonenumber-js: 0.4.31 => 0.4.31
lint-staged: 8.1.5 => 8.1.5
lodash: 4.17.11 => 4.17.11
metro-react-native-babel-preset: 0.56.0 => 0.56.0
moment: 2.24.0 => 2.24.0
moment-duration-format: ^2.3.2 => 2.3.2
moment-timezone: 0.5.26 => 0.5.26
prettier: 1.17.0 => 1.17.0
prettier-eslint: 8.8.2 => 8.8.2
prop-types: 15.7.2 => 15.7.2
react: 16.9.0 => 16.9.0
react-dom: 16.8.6 => 16.8.6
react-intl-native: 2.1.2 => 2.1.2
react-native: 0.61.5 => 0.61.5
react-native-adjust: 4.18.2 => 4.18.2
react-native-animatable: 1.3.3 => 1.3.3
react-native-device-info: 5.3.1 => 5.3.1
react-native-dotenv: 0.2.0 => 0.2.0
react-native-fbsdk: 1.1.1 => 1.1.1
react-native-fs: 2.16.2 => 2.16.2
react-native-geolocation-service: 3.1.0 => 3.1.0
react-native-gesture-handler: 1.5.2 => 1.5.2
react-native-google-maps: 1.0.0 => 1.0.0
react-native-htmlview: 0.14.0 => 0.14.0
react-native-keyboard-accessory: 0.1.10 => 0.1.10
react-native-keyboard-aware-scroll-view: 0.9.1 => 0.9.1
react-native-linear-gradient: 2.5.6 => 2.5.6
react-native-localize: ^1.3.1 => 1.3.1
react-native-mail: 4.1.0 => 4.1.0
react-native-map-link: 2.5.2 => 2.5.2
react-native-maps: 0.26.1 => 0.26.1
react-native-page-control: 1.1.1 => 1.1.1
react-native-permissions: ^2.0.4 => 2.0.8
react-native-reanimated: ^1.4.0 => 1.4.0
react-native-screens: 2.0.0-alpha.13 => 2.0.0-alpha.13
react-native-splash-screen: 3.2.0 => 3.2.0
react-native-svg: 9.13.3 => 9.13.3
react-native-swiper: ^1.6.0-rc.3 => 1.6.0-rc.3
react-native-webview: 7.5.2 => 7.5.2
react-navigation: 4.0.10 => 4.0.10
react-navigation-animated-switch: ^0.3.2 => 0.3.2
react-navigation-drawer: ^2.3.3 => 2.3.3
react-navigation-hooks: 1.1.0 => 1.1.0
react-navigation-stack: ^1.10.3 => 1.10.3
react-redux: 7.1.3 => 7.1.3
redux: 4.0.4 => 4.0.4
redux-logger: 3.0.6 => 3.0.6
redux-mock-store: 1.5.3 => 1.5.3
redux-persist: 6.0.0 => 6.0.0
redux-saga: 0.16.0 => 0.16.0
redux-thunk: 2.3.0 => 2.3.0
rxjs: 6.4.0 => 6.4.0
sonar-scanner: 3.1.0 => 3.1.0
source-map: ^0.7.3 => 0.7.3
uuid-js: 0.7.5 => 0.7.5
yarn: ^1.19.2 => 1.21.1
npmGlobalPackages:
@nestjs/cli: 6.6.3
bit-bin: 14.4.3
expo-cli: 3.4.1
gatsby-cli: 2.8.19
npm: 6.10.0

```

@mickadoua Thank you I will try to use this to fix issue tommorow and reach out if I have any further problems.

@mickadoua @ajdinahmetovic
Yours scenario seems very similar to mine.
The very weird aspect of this issue is that it shows suddenly out.
Read my post above: I didn't change any dependencies from my project but suddenly the currentAuthenticatedUser stopped working.
https://github.com/aws-amplify/amplify-js/issues/4351#issuecomment-566555291

How can it happens? I mean without updating dependencies how is it possible it suddenly stopped working? 🤔

I am having the same issue. It was working fine for month and then stopped working after minor version update. Rolling back to version I was using before or updating to latest have not worked. In my case I am doing federatedSignIn it works fine and calling currentAuthenticatedUser({ bypassCache: true }) right after signIn returns user data. However after app reload calling currentAuthenticatedUser({ bypassCache: true }) returns Not authenticated error. Doing just currentAuthenticatedUser() works

I am having the issue now as well. It seemed fixed before, but the same as with @claudioviola it is not working anymore even though I did not update aws-amplify

I'm still having this issue. Sometimes it works well, but just a few times. It's really weird and frustrating.
Update:
@anthonyhumphreys solution works yet!
So, the issue sholud be reopened!

@Ashish-Nanda This issue should indeed be reopened:

My package.json:

    "amazon-cognito-identity-js": "^3.2.0",
    "aws-amplify": "^2.1.0",

I have also tried using "aws-amplify" 2.2.0 and this did not fix the issue.
Also tried calling Auth.currentAuthenticatedUser({ bypassCache: true }) - also does not fix the issue.

Closing the app and reopening it sometimes does and sometimes does not remove the Cognito user session.

If I go to node_modules/@aws-amplify/core/src/RNComponents/reactnative.ts i see that it is still using the old AsyncStorage:

Screenshot 2020-01-23 at 15 52 45

Same in node_modules/@aws-amplify/core/src/StorageHelper/reactnative.ts:

Screenshot 2020-01-23 at 15 53 45

And package.json in node_modules/@aws-amplify/core/package.json says version: "2.2.1"
If I upgrade to aws-amplify version 2.2.0 I see the same Async Storage import from react-native core.

@KristineTrona what version of react native are you using? The issue was not related to not using the community edition of AsyncStorage, since it is still part of react native (atleast till 0.61.5) and there are some more details in this comment

Please give some more details about your project, and maybe some sample code so we can try to repro the issue you are having. Regarding the user credentials not being persisted, does it only happen when you kill the app? How consistently does it happen? Please give a few repro steps to ensure we can try it the same way.

@Ashish-Nanda Thanks for the reply - I am using RN 0.61.4, no expo. In my project I am initially rendering a launch screen and checking whether there is a current authenticated cognito user and based on that route the user to either home screen or login screen respectively.

In LaunchScreen.js:

  async componentDidMount() {
    const { navigation } = this.props;

    try {
      await Auth.currentAuthenticatedUser();
      navigation.navigate('HomeScreen');
    } catch (e) {
      navigation.navigate(‘LoginScreen');
    }
}

Sometimes re-opening the app does not cause any problems, but sometimes it does. It is very random. I had created a build and reopened the app 10 times to test it and 10/10 times did not encounter the problem. Then suddenly it started to happen again. I have a feeling it fails mostly on an actual device with a release build, and not on the simulator. I am also only testing using iOS, and the app is being built for an iPad, not iPhone.

Also as a temporary fix I implemented the fix suggested by @anthonyhumphreys and that seems to be working without any issues so far, which makes me really believe that something could be wrong with the AsyncStorage. Hope this helps to reproduce the issue.

I'm getting a similar error, where after authentication I can get files from my S3 bucket. the logs reflect this:

[DEBUG] 00:39.767 Credentials - getting credentials ConsoleLogger.js:76 [DEBUG] 00:39.768 Credentials - picking up credentials ConsoleLogger.js:76 [DEBUG] 00:39.769 Credentials - getting new cred promise ConsoleLogger.js:76 [DEBUG] 00:39.769 Credentials - checking if credentials exists and not expired ConsoleLogger.js:76 [DEBUG] 00:39.771 Credentials - credentials not changed and not expired, directly return ConsoleLogger.js:83 [DEBUG] 00:39.773 AWSS3Provider - set credentials for storage {accessKeyId: "xxx", sessionToken: "xxx", secretAccessKey: "xxx", identityId: "xxxx", authenticated: true}

But on app reload these credentials are not persisted:

[DEBUG] 06:34.92 Credentials - getting credentials ConsoleLogger.js:76 [DEBUG] 06:34.93 Credentials - picking up credentials ConsoleLogger.js:76 [DEBUG] 06:34.94 Credentials - getting new cred promise ConsoleLogger.js:76 [DEBUG] 06:34.95 Credentials - checking if credentials exists and not expired ConsoleLogger.js:76 [DEBUG] 06:34.96 Credentials - need to get a new credential or refresh the existing one ConsoleLogger.js:76 [DEBUG] 06:34.98 AuthClass - Getting current user credentials ConsoleLogger.js:76 [DEBUG] 06:34.101 Credentials - Getting federated credentials ConsoleLogger.js:76 [DEBUG] 06:34.101 Credentials - checking if federated jwt token expired ConsoleLogger.js:83 [DEBUG] 06:34.102 Credentials - no refresh handler for provider: xxx.auth0.com ConsoleLogger.js:76 [DEBUG] 06:34.104 AsyncStorageCache - Remove item: key is federatedInfo backend.js:32 [WARN] 06:34.106 AWSS3Provider - ensure credentials error no refresh handler for provider69 Bio.tsx:51 No credentials

Dependencies are:

    "@react-native-community/async-storage": "^1.9.0",
    "aws-amplify": "2.2.2",
    "aws-amplify-react-native": "^4.0.4",
    "react-native": "0.62.2",

How can I persist/ fetch credentials on app reload to stop this occuring?

I'm using the following and have this exact issue... when reloading, login is not persisted. There are so many comments/workarounds on here but I'm unsure which one I'm supposed to do, or if it's supposed to be working/patched now considering this issue is closed?

"aws-amplify": "^3.0.16",
"expo": "~37.0.9",
"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",

I'm getting this same error without expo...still
"aws-amplify": "^3.0.11",
"aws-amplify-react": "^4.1.10",
"bootstrap": "^4.5.0",
"formik": "^2.1.4",
"react": "^16.13.1",

Here I am not using storage in config.

I need to reload the app after logout to navigate the login screen

@Ashish-Nanda why is this issue closed? It seems that many users are still having this problem, and there is an active and continuing stream of posts about this. I would also point out that this is not only a react problem - I am having the exact same behavior in my vue application.

We are also having this issue. Quite frustrated having chosen Amplify due to it being touted as an out-of-the-box solution. Our experience has been anything but...

This issue is definitely not resolved. We had all workarounds implemented (including custom MemoryStorage that uses non-deprecated AsyncStorage import) but still had issues with users being logged out await Auth.currentAuthenticatedUser(); was still randomly throwing and logs confirmed that. Worst of all there was absolutely no pattern for that and we could not replicate that in controlled environment. Our experience with Amplify was a nightmare. In the end we've decided that it is easier for us to switch to different auth service.

@Shaninnik unfortunately we're stuck with it for AWS integration...

I've spent the last day and a half or so trying different approaches to solving this issue: implementing custom storage class, using refreshHandlers... to no avail. Its frustrating because user login via Cognito IdP (email, password) works just fine and doens't experience this issue.

I am having the same issue, I tried with a custom storage class, and I realized that although the currentAuthenticatedUser function returns undefined, when the storage´s getItem function is called, the session values are returned by AsyncStorage, for some reason the currentAuthenticatedUser function cannot access to those values. if we print in console the requested values inside storage class´s sync and getItem functions, session values are returned

Captura
image

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ldgarcia picture ldgarcia  ·  3Comments

guanzo picture guanzo  ·  3Comments

DougWoodCDS picture DougWoodCDS  ·  3Comments

oste picture oste  ·  3Comments

shinnapatthesix picture shinnapatthesix  ·  3Comments