Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetchAuthSession returns object with undefined values #13648

Closed
3 tasks done
sgoy-suzutatsu opened this issue Jul 26, 2024 · 15 comments
Closed
3 tasks done

fetchAuthSession returns object with undefined values #13648

sgoy-suzutatsu opened this issue Jul 26, 2024 · 15 comments
Assignees
Labels
Auth Related to Auth components/category Next.js question General question

Comments

@sgoy-suzutatsu
Copy link

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

REST API

Amplify Version

v6

Amplify Categories

auth

Backend

None

Environment information

"@datadog/browser-logs": "5.6.0",
"@sentry/electron": "4.15.1",
"@sentry/nextjs": "7.77.0",
"@sentry/tracing": "7.77.0",
"@tanstack/react-query": "5.8.7",
"@tanstack/react-query-next-experimental": "5.8.7",
"@tanstack/react-table": "^8.10.7",
"aws-amplify": "6.0.23",
"dayjs": "1.11.10",
"dotenv": "^16.3.1",
"electron-is-dev": "2.0.0",
"electron-log": "^5.1.0",
"electron-next": "3.1.5",
"electron-updater": "^6.1.7",
"launchdarkly-react-client-sdk": "3.0.10",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-toastify": "^9.1.3",
"react-use": "17.4.2",
"reset-css": "^5.0.2"
"@biomejs/biome": "1.4.1",
"@faker-js/faker": "8.3.1",
"@playwright/test": "1.40.1",
"@storybook/addon-backgrounds": "7.6.6",
"@storybook/addon-essentials": "7.6.6",
"@storybook/addon-interactions": "7.6.6",
"@storybook/addon-links": "7.6.6",
"@storybook/addon-onboarding": "1.0.10",
"@storybook/blocks": "7.6.6",
"@storybook/nextjs": "7.6.6",
"@storybook/react": "7.6.6",
"@storybook/testing-library": "0.2.2",
"@testing-library/jest-dom": "6.1.6",
"@testing-library/react": "14.0.0",
"@types/jest": "29.5.11",
"@types/node": "20.8.10",
"@types/react": "18.2.45",
"@types/react-dom": "18.2.18",
"cross-fetch": "4.0.0",
"electron": "24.6.4",
"electron-builder": "24.6.4",
"eslint": "8.56.0",
"faker": "^5.5.3",
"http-server": "14.1.1",
"husky": "8.0.3",
"hygen": "6.2.11",
"jest": "29.7.0",
"jest-environment-jsdom": "29.7.0",
"lint-staged": "15.0.2",
"msw": "2.0.11",
"next": "14.0.4",
"npm-run-all": "4.1.5",
"openapi2aspida": "0.23.2",
"orval": "6.20.0",
"rimraf": "5.0.5",
"sass": "1.69.5",
"start-server-and-test": "^2.0.3",
"storybook": "7.6.6",
"style-dictionary": "^3.9.0",
"stylelint": "16.0.2",
"stylelint-config-recess-order": "4.4.0",
"stylelint-config-recommended-scss": "14.0.0",
"stylelint-config-standard-scss": "12.0.0",
"ts-jest": "^29.1.1",
"ts-node": "10.9.2",
"typed-scss-modules": "8.0.0",
"typescript": "5.2.2"

Describe the bug

amplify in aws and using nextjs with existing endpoints.
English is not good enough.

言葉の問題で説明が不明瞭であれば申し訳ない。

背景

  • 静的生成でNext.jsを使っている
  • 1分ごとにAPIコールで新しい情報を取得するポーリングを実装している
  • Cognito認証の詳細
    • トークンの有効期限 1時間
    • リフレッシュトークンの有効期限:24時間

アプリケーションにログインした後、ポーリングが開始され、1分ごとに新しい情報がフェッチされます。このプロセスの間、トークンを利用するために毎回 fetchAuthSession が呼び出されます。トークンの有効期限が1時間後、リフレッシュトークンの有効期限が24時間後であることを考えると、理論的には24時間継続してアプリケーションを使用できるはずです。

しかし、実際の動作は異なります。およそ1時間に1回(変動はありますが)、トークンのリフレッシュのタイミングで、fetchAuthSessionが空のオブジェクトを返すことがあります。参考までに関連するコードを添付しておきます。

トークンの有効期限切れイベントをログに記録していますが、興味深いことに、これらのログはトークンが正常に取得されていることを示唆しています。これらのログの失敗したトークンは、異なる日付にまたがって同じように見えることは注目に値します。添付画像のトークンは、元の形式を保護するためにハッシュ化されている。

同じような問題を検索していたところ、同じような現象に関する報告がいくつか見つかりましたが、私たちの環境と完全に一致するものはありませんでした。
CleanShot 2024-07-26 at 18 49 52

Expected behavior

The expected behavior is that fetchAuthSession should continue to return tokens and other information as long as it's within the 24-hour period.

Reproduction steps

Steps to Reproduce:

  1. Implement polling that occurs once every minute.
  2. Call fetchAuthSession with each poll.
  3. Check if a failure occurs approximately once every hour.

Note: This procedure does not guarantee 100% reproducibility.
The issue may be more likely to occur when multiple users are utilizing the same Cognito information.

Code Snippet

// Put your code below this line.
export const fetchCurrentSession = async (options?: {
  forceRefresh: boolean;
}): Promise<AuthSessionResult> => {
  const deviceId = getItem(LOCAL_STORAGE_KEYS.DEVICE_ID_KEY);
  let session;
    session = await fetchAuthSession(options);

  if (!session.tokens) {
    consoe("Session does not contain any tokens.", {
      session: JSON.stringify(session),
      options: JSON.stringify(options),
      deviceId: deviceId || null,
    });
    return {
      jwtToken: "",
      isTokenExpired: () => false,
    };
  }

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

No response

@sgoy-suzutatsu sgoy-suzutatsu added the pending-triage Issue is pending triage label Jul 26, 2024
@israx
Copy link
Member

israx commented Jul 26, 2024

Hello @sgoy-suzutatsu. Sorry to hear you are experiencing issues with the library.

The fetchAuthSession API will return undefined tokens when the user is not authenticated or if the refresh_token is expired.

You can listen to the tokenRefresh_failure hub event and console log the payload data to see if you are getting any errors. If that event is dispatched, it means you need to re-authenticate to get a new refresh_token.

@cwomack
Copy link
Member

cwomack commented Jul 26, 2024

Going to attempt to add a translation to the issue here to help us @sgoy-suzutatsu. Let me know if this is correct:

I apologize if my explanation is unclear due to language issues.

background

Using Next.js for static generation
Implements polling that retrieves new information with API calls every minute.
Cognito authentication details
Token expiration time 1 hour
Refresh token expiry: 24 hours
After logging into the application, polling will start and new information will be fetched every minute. During this process, fetchAuthSession is called each time to redeem the token. Given that the token expires after 1 hour and the refresh token expires after 24 hours, you should theoretically be able to use your application continuously for 24 hours.

However, the actual behavior is different. Approximately once every hour (with some variation), fetchAuthSession may return an empty object when the token is refreshed. I have attached the relevant code for your reference.

I am logging token expiration events, but interestingly these logs suggest that the token is being successfully retrieved. It's worth noting that the failed tokens in these logs look the same across different dates. The attached image token has been hashed to protect its original format.

While searching for a similar issue, I found several reports of similar phenomena, but none that exactly matched our environment.

@cwomack cwomack self-assigned this Jul 26, 2024
@cwomack cwomack added Auth Related to Auth components/category Next.js labels Jul 26, 2024
@cwomack
Copy link
Member

cwomack commented Jul 26, 2024

@sgoy-suzutatsu, it looks like you're on v6.0.23 of Amplify. Just to see if we can determine if this was an older bug that was fixed, can you see if upgrading to the latest version resolves the issue (v6.4.3 currently at the time of this comment)?

If not, can you take a look at #13486 to see if that describes what you're experiencing? And can you clarify if you are seeing this behavior under the following scenarios:

  • When the app goes offline
  • When the access token expires

@cwomack cwomack added question General question pending-response and removed pending-triage Issue is pending triage labels Jul 26, 2024
@sgoy-suzutatsu
Copy link
Author

@cwomack @israx
Thank you for your response. We will try the suggested solutions and logging methods. Here's some additional information that might help identify the cause:

Regarding the reproduction of the session expiring within 24 hours, it seems to occur when the same application is used on multiple devices simultaneously.

Our understanding is that different tokens should be issued for each device since they are separate instances. However, could there be some form of token conflict or interference occurring due to this multi-device usage?

Any insights into this aspect of the issue would be greatly appreciated.

@sgoy-suzutatsu
Copy link
Author

@cwomack

  • Regarding the app going offline:
    After checking, we found that the issue does not reproduce when the app is offline.

  • When the access token expires:
    In this case, an empty object was returned when the token expired.
    We believe this is the expected behavior.

@sgoy-suzutatsu
Copy link
Author

sgoy-suzutatsu commented Aug 2, 2024

@cwomack @israx
I obtained the following log when reproducing the issue:

{
  "payload": {
    "data": {
      "error": {
        "constructor": "[Function]",
        "name": "NotAuthorizedException"
      }
    },
    "event": "tokenRefresh_failure"
  }
}

Does this mean that the refresh token is not functioning correctly and the token is not being refreshed after the 1-hour expiration period?
Additionally, I found that this issue seems similar to the following:
#12763

Even after updating Amplify to the latest version, the same issue seems to be occurring.

@cwomack
Copy link
Member

cwomack commented Aug 13, 2024

@sgoy-suzutatsu, thank you for the additional logs and follow up here. If you're receiving the tokenRefresh_failure, this is something we'd expect to happen when the refresh token service call gets rejected. I know you provided details for this already when this issue was opened, but can you just double check to see if the refresh token expiration settings differ from 24 hours TTL (within Cognito console)? And could you also provide a screenshot or full log of the corresponding failing network request to the Cognito endpoint to see if we can see a reason for rejection in the response?

@farhan-helmy
Copy link

still havent resolve, i have similar problem with next js app router + aws-amplify package, alreadt upgraded to the latest version, somehow the idtoken is undefined, i need to use it to fetch the api :(

@cwomack
Copy link
Member

cwomack commented Sep 10, 2024

@farhan-helmy, are you able to provide more details on how you're TTL settings are configured within your app or provide a screenshot/full log of the corresponding failing network requests to the Cognito endpoint? If you're experiencing the same errors with undefined values, we can continue it within this issue or feel free to open a new one yourself to capture your environment details.

But are you also experiencing this with the Auth category or another? Any additional information on the API's you're calling when this happens would be appreciated.

@cwomack cwomack added pending-community-response Issue is pending a response from the author or community. and removed pending-response labels Sep 10, 2024
@thejasonxie
Copy link

thejasonxie commented Sep 19, 2024

Hello @sgoy-suzutatsu. Sorry to hear you are experiencing issues with the library.

The fetchAuthSession API will return undefined tokens when the user is not authenticated or if the refresh_token is expired.

You can listen to the tokenRefresh_failure hub event and console log the payload data to see if you are getting any errors. If that event is dispatched, it means you need to re-authenticate to get a new refresh_token.

@israx @cwomack is this still the case if all the cognito tokens are in localStorage? It seems like I'm getting undefined values with await fetchAuthSession even though my localStorage has all the valid tokens

Screenshot 2024-09-19 at 10 11 12 AM

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Sep 19, 2024
@cwomack cwomack removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Oct 8, 2024
@cwomack
Copy link
Member

cwomack commented Oct 8, 2024

@thejasonxie, the default behavior for token storage in Amplify is to use localStorage. This can be customized to use different token management options, but it doesn't sound like you've customized anything beyond the "out of the box" setup for Auth. Is this correct?

@cwomack cwomack added the pending-community-response Issue is pending a response from the author or community. label Oct 8, 2024
@cwomack
Copy link
Member

cwomack commented Oct 8, 2024

Also wanted to follow up with @farhan-helmy and @sgoy-suzutatsu. There were follow up questions/comments above, but let us know if you're still blocked here!

@thejasonxie
Copy link

@thejasonxie, the default behavior for token storage in Amplify is to use localStorage. This can be customized to use different token management options, but it doesn't sound like you've customized anything beyond the "out of the box" setup for Auth. Is this correct?

Yes i only want to use defaults. For more context, I was trying to make a wrapper package around aws-amplify and I thought this would work since it should be checking localStorage by default but it seems even when strictly configured for localStorage, the issue is still the same.

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Oct 9, 2024
@cwomack
Copy link
Member

cwomack commented Oct 14, 2024

@thejasonxie, just to ensure we can separate the OP's issue from yours here... would you mind opening up a new issue so we can capture your environments information, code that reproduces this, etc? Given that you're using a wrapper package, we might need more context and steps to reproduce.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Oct 14, 2024
@cwomack
Copy link
Member

cwomack commented Oct 14, 2024

@sgoy-suzutatsu, we'll close this issue as we have not heard back from you. If you are still experiencing this, please feel free to reply back and provide any information previously requested and we'd be happy to re-open the issue.

Thank you!

@cwomack cwomack closed this as not planned Won't fix, can't repro, duplicate, stale Oct 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Auth Related to Auth components/category Next.js question General question
Projects
None yet
Development

No branches or pull requests

5 participants