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

Session tokens are empty although user signed in #13906

Closed didemkkaslan closed 1 month ago

didemkkaslan commented 1 month ago

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Version

v6

Amplify Categories

auth

Backend

CDK

Environment information

``` # Put output below this line System: OS: macOS 14.6.1 CPU: (8) arm64 Apple M2 Memory: 161.08 MB / 8.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 18.16.0 - /usr/local/bin/node Yarn: 1.22.22 - /opt/homebrew/bin/yarn npm: 9.5.1 - /usr/local/bin/npm pnpm: 9.10.0 - /usr/local/bin/pnpm bun: 1.0.2 - ~/.bun/bin/bun Browsers: Chrome: 129.0.6668.100 Safari: 18.0.1 npmPackages: @amplitude/analytics-browser: ^2.3.3 => 2.11.1 @ampproject/toolbox-optimizer: undefined () @ant-design/cssinjs: 1.20.0 => 1.20.0 (1.21.1) @ant-design/icons: ^5.2.6 => 5.4.0 @ant-design/plots: 1.2.5 => 1.2.5 @aws-amplify/adapter-nextjs: 1.2.9 => 1.2.9 @aws-amplify/adapter-nextjs/api: undefined () @aws-amplify/adapter-nextjs/data: undefined () @azure/msal-browser: ^3.24.0 => 3.24.0 @azure/msal-react: ^2.1.0 => 2.1.0 @babel/core: undefined () @babel/runtime: 7.15.4 @edge-runtime/cookies: 4.0.2 @edge-runtime/ponyfill: 2.4.1 @edge-runtime/primitives: 4.0.2 @graphql-codegen/cli: 5.0.0 => 5.0.0 @graphql-codegen/client-preset: 4.1.0 => 4.1.0 @graphql-codegen/introspection: 4.0.0 => 4.0.0 @hapi/accept: undefined () @mantine/hooks: ^7.1.5 => 7.12.2 @microsoft/teams-js: ^2.19.0 => 2.28.0 @mswjs/interceptors: undefined () @napi-rs/triples: undefined () @next/bundle-analyzer: ^13.5.6 => 13.5.6 @next/font: undefined () @next/react-dev-overlay: undefined () @opentelemetry/api: undefined () @react-pdf/renderer: ^3.1.13 => 3.4.4 @segment/ajv-human-errors: undefined () @tailwindcss/typography: ^0.5.10 => 0.5.15 @tanstack/query-codemods: undefined () @tanstack/react-query: ^5.0.5 => 5.54.1 @tanstack/react-query-devtools: ^5.8.9 => 5.54.1 @testing-library/jest-dom: ^6.1.4 => 6.5.0 @testing-library/react: ^14.0.0 => 14.3.1 @testing-library/user-event: ^14.5.1 => 14.5.2 @types/jest: ^29.5.6 => 29.5.12 @types/lodash: ^4.14.200 => 4.17.7 @types/mixpanel-browser: ^2.47.4 => 2.50.0 @types/node: ^20.8.8 => 20.16.5 (22.5.4) @types/react: ^18.2.31 => 18.3.5 @types/react-dom: ^18.2.14 => 18.3.0 @types/react-google-recaptcha: ^2.1.7 => 2.1.9 @types/react-highlight-words: ^0.16.6 => 0.16.7 @types/uuid: ^9.0.7 => 9.0.8 @typescript-eslint/eslint-plugin: ^6.9.0 => 6.21.0 @typescript-eslint/parser: ^6.9.0 => 6.21.0 @vercel/nft: undefined () @vercel/og: undefined () acorn: undefined () amphtml-validator: undefined () anser: undefined () antd: 5.17.0 => 5.17.0 apexcharts: ^3.44.0 => 3.53.0 arg: undefined () assert: undefined () async-retry: undefined () async-sema: undefined () autoprefixer: ^10.4.16 => 10.4.20 aws-amplify: ^6.6.0 => 6.6.0 aws-amplify/adapter-core: undefined () aws-amplify/analytics: undefined () aws-amplify/analytics/kinesis: undefined () aws-amplify/analytics/kinesis-firehose: undefined () aws-amplify/analytics/personalize: undefined () aws-amplify/analytics/pinpoint: undefined () aws-amplify/api: undefined () aws-amplify/api/server: undefined () aws-amplify/auth: undefined () aws-amplify/auth/cognito: undefined () aws-amplify/auth/cognito/server: undefined () aws-amplify/auth/enable-oauth-listener: undefined () aws-amplify/auth/server: undefined () aws-amplify/data: undefined () aws-amplify/data/server: undefined () aws-amplify/datastore: undefined () aws-amplify/in-app-messaging: undefined () aws-amplify/in-app-messaging/pinpoint: undefined () aws-amplify/push-notifications: undefined () aws-amplify/push-notifications/pinpoint: undefined () aws-amplify/storage: undefined () aws-amplify/storage/s3: undefined () aws-amplify/storage/s3/server: undefined () aws-amplify/storage/server: undefined () aws-amplify/utils: undefined () aws-rum-web: ^1.15.0 => 1.19.0 axios: ^1.5.1 => 1.7.7 babel-packages: undefined () browserify-zlib: undefined () browserslist: undefined () buffer: undefined () bytes: undefined () ci-info: undefined () cli-select: undefined () client-only: 0.0.1 clsx: ^2.0.0 => 2.1.1 comment-json: undefined () compression: undefined () conf: undefined () constants-browserify: undefined () content-disposition: undefined () content-type: undefined () cookie: undefined () cookies-next: ^4.1.1 => 4.2.1 cross-spawn: undefined () crypto-browserify: undefined () css.escape: undefined () data-uri-to-buffer: undefined () dayjs: ^1.11.10 => 1.11.13 debug: undefined () devalue: undefined () docx: ^8.5.0 => 8.5.0 domain-browser: undefined () edge-runtime: undefined () eslint: ^8.52.0 => 8.57.0 eslint-config-airbnb: ^19.0.4 => 19.0.4 eslint-config-airbnb-typescript: ^17.1.0 => 17.1.0 eslint-config-next: ^13.5.6 => 13.5.6 eslint-config-prettier: ^9.0.0 => 9.1.0 eslint-plugin-i18next: ^6.0.3 => 6.0.9 eslint-plugin-import: ^2.29.0 => 2.30.0 eslint-plugin-jest: ^27.4.3 => 27.9.0 eslint-plugin-jest-dom: ^5.1.0 => 5.4.0 eslint-plugin-jsx-a11y: ^6.7.1 => 6.10.0 eslint-plugin-react: ^7.33.2 => 7.35.2 eslint-plugin-testing-library: ^6.1.2 => 6.3.0 events: undefined () find-cache-dir: undefined () find-up: undefined () framer-motion: ^10.16.4 => 10.18.0 fresh: undefined () get-orientation: undefined () glob: undefined () graphql: ^16.8.1 => 16.9.0 (15.8.0) graphql-request: ^6.1.0 => 6.1.0 gzip-size: undefined () http-proxy: undefined () http-proxy-agent: undefined () https-browserify: undefined () https-proxy-agent: undefined () husky: ^8.0.3 => 8.0.3 i18next: ^23.7.15 => 23.14.0 i18next-chained-backend: ^4.5.0 => 4.6.2 i18next-http-backend: ^2.2.2 => 2.6.1 i18next-localstorage-backend: ^4.2.0 => 4.2.0 icss-utils: undefined () ignore-loader: undefined () image-size: undefined () is-animated: undefined () is-docker: undefined () is-wsl: undefined () jest: ^29.7.0 => 29.7.0 jest-environment-jsdom: ^29.7.0 => 29.7.0 jest-worker: undefined () json5: undefined () jsonwebtoken: undefined () jwt-decode: ^3.1.2 => 3.1.2 loader-runner: undefined () loader-utils: undefined () lodash: ^4.17.21 => 4.17.21 lodash.curry: undefined () lru-cache: undefined () micromatch: undefined () mini-css-extract-plugin: undefined () mixpanel-browser: ^2.47.0 => 2.55.1 nanoid: undefined () native-url: undefined () neo-async: undefined () next: ^13.5.6 => 13.5.6 next-i18next: ^15.1.2 => 15.3.1 next-i18next-create-client: undefined () next-seo: ^6.1.0 => 6.6.0 node-fetch: undefined () node-html-parser: undefined () nookies: ^2.5.2 => 2.5.2 ora: undefined () os-browserify: undefined () p-limit: undefined () path-browserify: undefined () platform: undefined () postcss: ^8.4.31 => 8.4.45 (8.4.31) postcss-flexbugs-fixes: undefined () postcss-modules-extract-imports: undefined () postcss-modules-local-by-default: undefined () postcss-modules-scope: undefined () postcss-modules-values: undefined () postcss-preset-env: undefined () postcss-safe-parser: undefined () postcss-scss: undefined () postcss-value-parser: undefined () prettier: ^3.0.3 => 3.3.3 prettier-plugin-tailwindcss: ^0.5.6 => 0.5.14 process: undefined () punycode: undefined () querystring-es3: undefined () raw-body: undefined () react: 18.2.0 => 18.2.0 react-apexcharts: ^1.4.1 => 1.4.1 react-builtin: undefined () react-dom: 18.2.0 => 18.2.0 react-dom-builtin: undefined () react-dom-experimental-builtin: undefined () react-error-boundary: ^4.0.13 => 4.0.13 react-experimental-builtin: undefined () react-google-recaptcha: ^3.1.0 => 3.1.0 react-highlight-words: ^0.20.0 => 0.20.0 react-i18next: ^14.0.0 => 14.1.3 react-icons: ^4.11.0 => 4.12.0 react-infinite-scroll-component: ^6.1.0 => 6.1.0 react-is: 18.2.0 react-refresh: 0.12.0 react-server-dom-turbopack-builtin: undefined () react-server-dom-turbopack-experimental-builtin: undefined () react-server-dom-webpack-builtin: undefined () react-server-dom-webpack-experimental-builtin: undefined () regenerator-runtime: 0.13.4 sass-loader: undefined () scheduler-builtin: undefined () scheduler-experimental-builtin: undefined () schema-utils: undefined () semver: undefined () send: undefined () server-only: 0.0.1 setimmediate: undefined () sharp: ^0.32.6 => 0.32.6 shell-quote: undefined () source-map: undefined () stacktrace-parser: undefined () stream-browserify: undefined () stream-http: undefined () string-hash: undefined () string_decoder: undefined () strip-ansi: undefined () superstruct: undefined () tailwind-merge: ^1.14.0 => 1.14.0 tailwindcss: ^3.3.3 => 3.4.10 tar: undefined () terser: undefined () text-table: undefined () timers-browserify: undefined () tty-browserify: undefined () typescript: ^5.2.2 => 5.5.4 ua-parser-js: undefined () undici: undefined () unistore: undefined () usehooks-ts: ^2.9.1 => 2.16.0 util: undefined () uuid: ^9.0.1 => 9.0.1 vm-browserify: undefined () watchpack: undefined () web-vitals: undefined () webpack: undefined () webpack-sources: undefined () ws: undefined () zod: ^3.22.4 => 3.23.8 () zustand: ^4.5.2 => 4.5.5 npmGlobalPackages: @aws-amplify/cli: 12.12.6 corepack: 0.17.0 eas-cli: 12.4.1 expo-cli: 6.3.10 npm: 9.5.1 pnpm: 9.10.0 turbo: 2.1.2 ```

Describe the bug

I'm implementing the Microsoft SSO signup/signin feature using msal.js and amplify library. After user signs in with microsoft email (Hub fires signedIn event here ) fetchAuthSession call throws User needs to be authenticated to call this API errors. and session tokens are empty

Screenshot 2024-10-10 at 12 43 27 Screenshot 2024-10-10 at 12 44 45

Expected behavior

Session tokens should be filled after successful sign in

Reproduction steps

Use Amplify's signIn method right after signUp

Code Snippet

// Put your code below this line.

  const handleMicrosoftSSOSignUp = async () => {
    try {
      // Open Microsoft login popup
      const { idToken, account } = await msalInstance.loginPopup({
        scopes: ['openid', 'profile', 'email'],
      });
      console.log('Microsoft ID Token:', idToken);

      // Use Microsoft ID token to sign up through AWS Cognito
      // This may throw an error if the user already exists so we need to handle it
      await signUp({
        username: account.username,
        password: autoGeneratedPassword,
        options: {
          userAttributes: {
            email: account.username,
            'custom:msalIdtoken': idToken,
          },
        },
      });

      // Sign in using the custom auth flow
      const { nextStep } = await signIn({
        username: account.username,
        options: {
          authFlowType: 'CUSTOM_WITHOUT_SRP',
        },
      });

      console.log('nextStep:', nextStep);

      // Confirm sign in with custom challenge
      if (nextStep?.signInStep === 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE') {
        try {
          await confirmSignIn({
            challengeResponse: idToken,
          });
        } catch (error) {
          console.log('challenge error', error);
        }
      }
    } catch (error) {
      console.log({
        error,
      });

      if (error instanceof AuthError) {
        if (error.name === 'UsernameExistsException') {
          // User already exists so we can sign in
          message.info('User already exists. Signing in...');
          console.log(activeAccount);
          if (!activeAccount || !activeAccount.idToken) return;
          const { nextStep } = await signIn({
            username: activeAccount?.username,
            options: {
              authFlowType: 'CUSTOM_WITHOUT_SRP',
            },
          });
          console.log('nextStep:', nextStep);

          if (
            nextStep?.signInStep === 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE'
          ) {
            try {
              const confirmSignInOutput = await confirmSignIn({
                challengeResponse: activeAccount?.idToken,
              });

              console.log('confirmSignInOutput:', confirmSignInOutput);
            } catch (error) {
              console.log('challenge error', error);
            }
          }
        }
      }

      // const email = msalInstance.getAccount({
      //   homeAccountId: activeAccount?.homeAccountId,
      // })?.username;
    }
  };

Middleware
import { runWithAmplifyServerContext } from '@/shared/utils/amplifyServerUtils';
import { fetchAuthSession } from 'aws-amplify/auth/server';
import { NextRequest, NextResponse } from 'next/server';

export async function middleware(request: NextRequest) {
  const response = NextResponse.next();

  const authenticated = await runWithAmplifyServerContext({
    nextServerContext: { request, response },
    operation: async (contextSpec) => {
      try {
        const session = await fetchAuthSession(contextSpec, {});

        console.log('session', session);
        return (
          session.tokens?.accessToken !== undefined &&
          session.tokens?.idToken !== undefined
        );
      } catch (error) {
        console.log(error);
        return false;
      }
    },
  });

  console.log('authenticated', authenticated);

  const isAuthPage =
    request.nextUrl.pathname.startsWith('/login') ||
    request.nextUrl.pathname.startsWith('/register');

  if (authenticated) {
    // Don't show auth pages if already authenticated
    if (isAuthPage) {
      return NextResponse.redirect(new URL('/meetings', request.url));
    }
  }

  if (!authenticated) {
    // Allow access to public meeting report page
    if (request.nextUrl.pathname.startsWith('/meetings/public')) {
      return response;
    }

    // Allow access to public meeting report page
    if (request.nextUrl.pathname.startsWith('/meetings/public_ekmob')) {
      return response;
    }

    // Google sign in will redirect to /?code=... so we need to allow that through
    if (
      request.nextUrl.pathname === '/login' &&
      request.nextUrl.searchParams.get('code')
    ) {
      return response;
    }

    // Redirect to login page when on a page that requires authentication
    if (!isAuthPage) {
      return NextResponse.redirect(new URL('/login', request.url), {
        status: 303,
      });
    }
  }

  // Allow access to public pages
  return response;
}

export const config = {
  matcher: [
    '/',
    '/onboarding/:path*',
    '/meetings/:path*',
    '/people/:path*',
    '/library/:path*',
    '/settings/:path*',
    '/integration/:path*',
    '/tags',
    '/login',
    '/register',
    '/realtime/:path*',
  ],
};

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

ashika112 commented 1 month ago

@didemkkaslan Thanks for opening up the issue. Some clarifying question once signedIn do you re-direct the customers to a new page than that of where the signIn originated from? From looks of the codde you provided that seems to be the case?

Have you followed our guideline on MPA and redirects in the case?

HuiSF commented 1 month ago

Hi @didemkkaslan thanks for opening this issue, I have some questions for your to help investigation:

  1. Have you configured Amplify on the client-side of your Next.js project by calling Amplify.configure(config, { ssr: true }) (note the second parameter ssr: true is required)
  2. It looks like the code in shared/config/configureAmplify.ts is running on the client-side, is that correct? Could you verify the fetchAuthSession() call was executed after the completion of your handleMicrosoftSSOSignUp() call?
  3. The fetchAuthSession() failed because the incoming request cookie header doesn't contain auth tokens. Could you verify whether the cookie header value of the corresponding request (you can do this by inspecting the request in Chrome developer tool, network tab)
didemkkaslan commented 1 month ago

@HuiSF Yes I've configured Amplify on client side using ssr: true .

Calling configureAmplify(); in _app.tsx file and its called on initial page load so long before microsoft signup function is called.

import amplifyconfig from '../../amplifyconfiguration.json';
import { Amplify } from 'aws-amplify';
import { fetchAuthSession } from 'aws-amplify/auth';
import { parseAmplifyConfig } from 'aws-amplify/utils';
import { createKeyValueStorageFromCookieStorageAdapter } from 'aws-amplify/adapter-core';
import { deleteCookie, getCookie, setCookie, getCookies } from 'cookies-next';
import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';

const amplifyConfig = parseAmplifyConfig(amplifyconfig);

const cookieOptions =
  process.env.NEXT_PUBLIC_ENV === 'msteams'
    ? {
        domain: 'tab.app.spiky.ai' as string,
        sameSite: 'none' as 'lax' | 'strict' | 'none',
        secure: true,
      }
    : {};

const keyValueStorage = createKeyValueStorageFromCookieStorageAdapter({
  get(name) {
    const value = getCookie(name, cookieOptions);
    return { name, value };
  },
  getAll() {
    const cookies = getCookies(cookieOptions);
    return Object.keys(cookies).map((name) => ({ name, value: cookies[name] }));
  },
  set(name, value) {
    setCookie(name, value, cookieOptions);
  },
  delete(name) {
    deleteCookie(name, cookieOptions);
  },
});

export const getAuthToken = async () => {
  const session = await fetchAuthSession({});
  return session.tokens?.idToken?.toString() as string;
};

export function configureAmplify() {
  Amplify.configure(
    {
      ...amplifyConfig,
      Auth: {
        ...amplifyConfig.Auth,
        Cognito: {
          ...amplifyConfig.Auth?.Cognito,
          identityPoolId:
            process.env.NEXT_PUBLIC_PLATFORM_COGNITO_IDENTITY_POOL_ID!,
          userPoolId: process.env.NEXT_PUBLIC_PLATFORM_COGNITO_USER_POOL_ID!,
          userPoolClientId:
            process.env.NEXT_PUBLIC_PLATFORM_COGNITO_USER_POOL_WEB_CLIENT_ID!,
        },
      },
      API: {
        ...amplifyConfig.API,
        REST: {
          ...amplifyConfig.API?.REST,
          PlatformCorePublicRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_ENDPOINT}/public`,
          },
          PlatformCoreRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_ENDPOINT}/platform`,
          },
          PlatformCoreCalendarRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_ENDPOINT}/calendar-v2`,
          },
          PlatformCoreTeamsRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_CORE_REST_API_TEAMS_ENDPOINT}`,
          },
          PlatformIntegrationRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_INTEGRATION_REST_API_ENDPOINT}`,
          },
          PlatformRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_REST_API_ENDPOINT}`,
          },
        },
      },
    },
    {
      ssr: true,
      API: {
        REST: {
          headers: async () => ({
            Authorization: `Bearer ${await getAuthToken()}`,
          }),
        },
      },
    },
  );

  cognitoUserPoolsTokenProvider.setKeyValueStorage(keyValueStorage);
}

UserAlreadyExistsException is thrown here and then I call signIn and here are the following network request two of them has no cookie header and the last one has smth weird

Screenshot 2024-10-11 at 01 12 05 Screenshot 2024-10-11 at 01 13 55 Screenshot 2024-10-11 at 01 14 49
didemkkaslan commented 1 month ago

@ashika112 I've also tried to place bunch of import 'aws-amplify/auth/enable-oauth-listener'; at the top of some files like register app.tsx but it didn't fix my problem. Sometimes refreshing the page authenticated returns true and tokens are full. but another refresh causes them to disappear

Screenshot 2024-10-11 at 01 18 46
HuiSF commented 1 month ago

Hi @didemkkaslan thanks for the details, a few things:

  1. createKeyValueStorageFromCookieStorageAdapter is not meant to be used for client-side use cases. If you want to custom the CookieStorage used on the client-side, please follow this documentation: https://docs.amplify.aws/gen1/react/build-a-backend/auth/manage-user-session/#update-your-token-saving-mechanism (Please keep in mind that currently adapter-nextjs doesn't support configuring cookie domain attribute on the server side)
  2. Could you verify whether Amplify was able to set the auth tokens in your browser cookie store with the code you shared after a successful signIn() call?
  3. You are setting cookie domain attribute as tab.app.spiky.ai does this match the host of the app you are testing with? (browser ignores mismatched domain cookies if current domain is different from the domain you set)
  4. When checking the request sent to your Next.js server that would be handled by the middleware, you would need to check document type request instead of fetch/xhr in the Network tab of the dev tool
didemkkaslan commented 1 month ago

Thanks @HuiSF I've checked the cookie store after successful sign in and only the accessToken, refreshToken , clockDrift, signInDetails, and LastAuthUser are exist. idToken is missing. A normal sign in with email & password idToken is generated but with microsoft sso its simply not there.

Screenshot 2024-10-11 at 07 44 56 Screenshot 2024-10-11 at 07 46 27

No tab.app.spiky.ai is not the domain I'm testing right now I'm testing localhost:3000. I've tried to remove custom cookie storage also but that also didn't work for me. I needed the custom cookie storage since we also have microsoft tab app and cookies weren't being stored there ( browser ignored them probably at that time ). Removing it, local storage had all these idtoken, accesstoken cookies but still I get the error.

I have also logged cookie header sent to Nextjs Server ( middleware )

_clck=1cx8bx6%7C2%7Cfpx%7C0%7C1745; hubspotutk=3970d3fef9a2ce6cf0ab058899bfb53d; __hssrc=1; _ga=GA1.1.833332417.1728621328; _gcl_au=1.1.173454892.1728621328; intercom-device-id-klkvftm2=28e6244f-edb0-49de-a5f2-47dd4eb81c0a; loginNumber=1; intercom-id-klkvftm2=21f3ec56-4953-4509-b95a-bc5f4040cfa8; intercom-session-klkvftm2=; hstc=181257784.3970d3fef9a2ce6cf0ab058899bfb53d.1728621327217.1728621327217.1728629861492.2; calendarModalShown=true; com.amplify.Cognito.us-east-2%3Afab77640-b14d-4c3f-9b28-4524f31ce036.identityId=us-east-2%3A17cd0c51-9013-c1c8-1815-d63a1ea89d5b; hssc=181257784.3.1728629861492; _clsk=azmhty%7C1728629941727%7C4%7C1%7Cs.clarity.ms%2Fcollect; _ga_2VPPWD0GX5=GS1.1.1728621327.1.1.1728629941.55.0.0; msal.interaction.status=3d3652ea-07fb-4bd9-aad7-9097b065e5b4; ph_phc_2m70xVenigl1M4tg2yTY6XzoCaZPO1F02xoHk2UAa1V_posthog=%7B%22distinct_id%22%3A%22019265d3-362b-771a-ae71-e228fda59435%22%2C%22%24sesid%22%3A%5B1728629985085%2C%2201927a5e-6bd8-7dbe-91ae-a6de6183c069%22%2C1728629861336%5D%7D

Screenshot 2024-10-11 at 10 02 42
didemkkaslan commented 1 month ago

Update: I've added forceRefresh: true to all the fetchAuthSession's and things started to work. User is successfully authenticated. Serverside fetchAuthSession calls now able to grab tokens. But I'm refreshing the token hundreds of time now and not sure if its the right way.

  const session = await fetchAuthSession(contextSpec, {
        forceRefresh: true,
      });
Screenshot 2024-10-11 at 17 20 15
const hubListenerCancelToken = Hub.listen('auth', async ({ payload }) => {
    console.log('auth event', payload);
})
HuiSF commented 1 month ago

Hi @didemkkaslan it sounds like some of your customizations may not work well to ensure a correct token writing flow. I'm getting lost in the threads of your use cases 😅 could you do the following:

  1. remove any custom CookieStorage implementation, and only use Amplify.configure(config, { ssr: true })
  2. Keep your integration of the Microsoft SSO
  3. remove any customization around calling fetchAuthSession
  4. The best: if you can provide a minimal sample app in a repo so I can help inspect the implementation as well

Then please let us know: what's working and what's not working

didemkkaslan commented 1 month ago

Hello @HuiSF I'm sorry I know it became a mess :D

I've done them all and it didn't work for me. Minimal sample repo prob is to hard to achieve because we use default cognito sources so my Amplify.configure is full of proces.envs.

I actually suspect idToken not being stored in cookie-storage. I got accessToken, signInDetails and all but idToken is not being stored.

https://github.com/aws-amplify/amplify-js/issues/11649#issuecomment-1641111040 This is also the same case for me. Using default storage I got idToken in localstorage but in cookie storage method its gone.

I've checked the size of it and its around 5000 bytes which goes beyond browser limit and maybe it just droppes.

Screenshot 2024-10-12 at 13 37 35 Screenshot 2024-10-12 at 13 38 09
didemkkaslan commented 1 month ago

Hello again:) This issue is solved and the reason this was happening was because indeed idToken was absent. It was an idToken size issue. Since it was bigger than 5000 bytest it was dropping silently. For anyone encountering this kind of session tokens empty problem I wanted to write this. Thanks for your patience and help Amplify team <3

cwomack commented 1 month ago

@didemkkaslan, thank you for following up and letting us know! Glad you're unblocked and we'll close out the issue now.

We also have the feature request captured within #11649 tracking this limitation as well, so keep an eye on that/follow it for updates as we have them. Thanks!