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

Confirm Signup Gives Me UserUnAuthenticatedException: User needs to be authenticated to call this API. #13071

Closed
3 tasks done
didemkkaslan opened this issue Feb 29, 2024 · 10 comments
Assignees
Labels
Auth Related to Auth components/category question General question

Comments

@didemkkaslan
Copy link

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.2.1
    CPU: (8) arm64 Apple M2
    Memory: 114.86 MB / 8.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.10.0 - ~/.nvm/versions/node/v20.10.0/bin/node
    Yarn: 1.22.19 - /opt/homebrew/bin/yarn
    npm: 10.2.3 - ~/.nvm/versions/node/v20.10.0/bin/npm
    pnpm: 8.13.1 - ~/.nvm/versions/node/v20.10.0/bin/pnpm
    bun: 1.0.2 - ~/.bun/bin/bun
  Browsers:
    Chrome: 122.0.6261.69
    Safari: 17.2.1
  npmPackages:
    @amplitude/analytics-browser: ^2.3.3 => 2.4.1 
    @ampproject/toolbox-optimizer:  undefined ()
    @ant-design/cssinjs: ^1.17.2 => 1.18.4 
    @ant-design/icons: ^5.2.6 => 5.3.0 
    @ant-design/plots: ^1.2.5 => 1.2.6 
    @aws-amplify/adapter-nextjs: ^1.0.9 => 1.0.16 
    @aws-amplify/adapter-nextjs/api:  undefined ()
    @aws-amplify/adapter-nextjs/data:  undefined ()
    @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.5.2 
    @microsoft/teams-js: ^2.16.0 => 2.20.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.3.8 
    @segment/ajv-human-errors:  undefined ()
    @tailwindcss/typography: ^0.5.10 => 0.5.10 
    @tanstack/query-codemods:  4.24.3 
    @tanstack/react-query: ^5.0.5 => 5.20.5 
    @tanstack/react-query-devtools: ^5.8.9 => 5.20.5 
    @testing-library/jest-dom: ^6.1.4 => 6.4.2 
    @testing-library/react: ^14.0.0 => 14.2.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.14.202 
    @types/mixpanel-browser: ^2.47.4 => 2.49.0 
    @types/node: ^20.8.8 => 20.11.17 
    @types/react: ^18.2.31 => 18.2.55 
    @types/react-dom: ^18.2.14 => 18.2.19 
    @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.10.2 => 5.10.2 
    apexcharts: ^3.44.0 => 3.45.2 
    arg:  undefined ()
    assert:  undefined ()
    async-retry:  undefined ()
    async-sema:  undefined ()
    autoprefixer: ^10.4.16 => 10.4.17 
    aws-amplify: 6.0.15 => 6.0.15 
    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/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.17.0 
    axios: ^1.5.1 => 1.6.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.0 
    comment-json:  undefined ()
    compression:  undefined ()
    conf:  undefined ()
    constants-browserify:  undefined ()
    content-disposition:  undefined ()
    content-type:  undefined ()
    cookie:  undefined ()
    cross-spawn:  undefined ()
    crypto-browserify:  undefined ()
    css.escape:  undefined ()
    data-uri-to-buffer:  undefined ()
    dayjs: ^1.11.10 => 1.11.10 
    debug:  undefined ()
    devalue:  undefined ()
    docx: ^8.5.0 => 8.5.0 
    domain-browser:  undefined ()
    edge-runtime:  undefined ()
    eslint: ^8.52.0 => 8.56.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.3 
    eslint-plugin-import: ^2.29.0 => 2.29.1 
    eslint-plugin-jest: ^27.4.3 => 27.8.0 
    eslint-plugin-jest-dom: ^5.1.0 => 5.1.0 
    eslint-plugin-jsx-a11y: ^6.7.1 => 6.8.0 
    eslint-plugin-react: ^7.33.2 => 7.33.2 
    eslint-plugin-testing-library: ^6.1.2 => 6.2.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.8.1 (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.8.2 
    i18next-chained-backend: ^4.5.0 => 4.6.2 
    i18next-http-backend: ^2.2.2 => 2.4.3 
    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.49.0 
    nanoid:  undefined ()
    native-url:  undefined ()
    neo-async:  undefined ()
    next: ^13.5.6 => 13.5.6 
    next-i18next: ^15.1.2 => 15.2.0 
    next-i18next-create-client:  undefined ()
    next-seo: ^6.1.0 => 6.4.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.35 (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.2.5 
    prettier-plugin-tailwindcss: ^0.5.6 => 0.5.11 
    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-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.0.5 
    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.1 
    tar:  undefined ()
    terser:  undefined ()
    text-table:  undefined ()
    timers-browserify:  undefined ()
    tty-browserify:  undefined ()
    typescript: ^5.2.2 => 5.3.3 
    ua-parser-js:  undefined ()
    undici:  undefined ()
    unistore:  undefined ()
    usehooks-ts: ^2.9.1 => 2.14.0 
    util:  undefined ()
    uuid: ^9.0.1 => 9.0.1 (8.3.2)
    vm-browserify:  undefined ()
    watchpack:  undefined ()
    web-vitals:  undefined ()
    webpack:  undefined ()
    webpack-sources:  undefined ()
    ws:  undefined ()
    zod: ^3.22.4 => 3.22.4 ()
  npmGlobalPackages:
    @aws-amplify/cli: 12.10.0
    corepack: 0.22.0
    eas-cli: 7.0.0
    npm: 10.2.3
    pnpm: 8.13.1


Describe the bug

We are building a Tab for microsoft teams. One of our pages /integration/microsoft-teams will be embedded inside microsoft teams app Spiky.ai tab. So I'm trying to authenticate user in this page.

if signUpWithMSTeamsToken gives me UsernameExistsException then I try to authenticate using signInWithMSTeamsToken function. where the error occurs.

export async function signInWithMSTeamsToken(
  username: string,
  idToken: string,
): Promise<SignInOutput> {
  console.log('signing in with ms teams token');
  const result = await signIn({
    username,
    options: {
      authFlowType: 'CUSTOM_WITHOUT_SRP',
    },
  });

  console.log(result);

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

  return Promise.resolve(result);
}

the last thing I see in the console is this 'confirming sign in with custom challenge' message. confirmSignIn throws UserUnAuthenticatedException: User needs to be authenticated to call this API. error.

This started to happen after migrating to amplify v6 the old working code was

export async function signInWithMSTeamsToken(
  username: string,
  idToken: string,
): Promise<CognitoUser> {
  const user = await Auth.signIn(username);
  await Auth.sendCustomChallengeAnswer(user, idToken);
  return Promise.resolve(user as CognitoUser);
}
Screenshot 2024-02-29 at 08 31 39

Expected behavior

It should complete the custom challenge with no errors and sign user in.

Reproduction steps

SignIn with CUSTOM_WITHOUT_SRP auth flow type and try to confirmSignIn

const result = await signIn({
    username,
    options: {
      authFlowType: 'CUSTOM_WITHOUT_SRP',
    },
  });

 await confirmSignIn({
        challengeResponse: idToken,
      });

Code Snippet

// Put your code below this line.

// /integration/microsoft-teams page
import {
  signInWithMSTeamsToken,
  signUpWithMSTeamsToken,
} from '@/auth/service/auth';
import PlatformPage from '@/shared/components/PlatformPage';
import * as microsoftTeams from '@microsoft/teams-js';
import { useQueryClient } from '@tanstack/react-query';
import { NextSeo } from 'next-seo';
import { useRouter } from 'next/router';
import { useState, useEffect, useCallback } from 'react';
import jwtDecode from 'jwt-decode';
import { Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { getCurrentUser } from 'aws-amplify/auth';

export default function MicrosoftTeamsIntegration() {
  const queryClient = useQueryClient();
  const router = useRouter();

  const [teamsContext, setTeamsContext] = useState({});
  const [userInfo, setUserInfo] = useState<{
    accessToken: string;
    email: string;
  }>();

  useEffect(() => {
    // only run client-side
    if (typeof window === 'undefined') return;
    microsoftTeams.app
      .initialize()
      .then(() => {
        microsoftTeams.app.notifyAppLoaded();
        microsoftTeams.app.notifySuccess();
        microsoftTeams.app.getContext().then((ctx) => {
          setTeamsContext(ctx);
        });
      })
      .then(() => {
        console.log('getting current user');
        getCurrentUser()
          .then((user) => {
            console.log('User:', user);
            router.push('/');
          })
          .catch(() => {
            microsoftTeams.authentication.getAuthToken({
              successCallback(accessToken) {
                const payload: {
                  preferred_username: string;
                } = jwtDecode(accessToken);

                setUserInfo({
                  accessToken,
                  email: payload.preferred_username,
                });
              },
            });
          });
      });
  }, [router]);

  const authenticateWithMSTeams = useCallback(() => {
    if (userInfo) {
      console.log('Authenticating with MS Teams');
      signInWithMSTeamsToken(userInfo.email, userInfo.accessToken).then(() => {
        console.log('Authenticated with MS Teams');
        queryClient.invalidateQueries({ queryKey: ['msTeamsAuth'] });
        // router.push('/');
      });
    }
  }, [queryClient, userInfo]);

  useEffect(() => {
    if (!userInfo) return;
    signUpWithMSTeamsToken(userInfo.email, userInfo.accessToken)
      .then(authenticateWithMSTeams)
      .catch(() => {
        // eslint-disable-next-line no-underscore-dangle

        authenticateWithMSTeams();
      });
  }, [authenticateWithMSTeams, userInfo]);

  return (
    <>
      <NextSeo
        description="Connect your Microsoft Teams account to the platform."
        title="Microsoft Teams"
      />
      <PlatformPage title="Microsoft Teams">
        <Spin indicator={<LoadingOutlined />} /> Connecting Microsoft Teams,
        please wait
        <pre>
          <b>Context:</b> {JSON.stringify(teamsContext, null, 2)}
        </pre>
      </PlatformPage>
    </>
  );
}

// auth/service/auth
import generatePassword from '../utils/generatePassword';
import {
  SignInOutput,
  signIn,
  signUp,
  SignUpOutput,
  confirmSignUp,
  ConfirmSignUpOutput,
  confirmSignIn,
} from 'aws-amplify/auth';

//  Methods for Microsoft Teams SSO

export async function signInWithMSTeamsToken(
  username: string,
  idToken: string,
): Promise<SignInOutput> {
  console.log('signing in with ms teams token');
  const result = await signIn({
    username,
    options: {
      authFlowType: 'CUSTOM_WITHOUT_SRP',
    },
  });

  console.log(result);

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

  return Promise.resolve(result);
}

export async function signUpWithMSTeamsToken(
  email: string,
  idToken: string,
): Promise<SignUpOutput> {
  const attributes = {
    email,
    'custom:msalIdtoken': idToken,
  };

  try {
    const result = await signUp({
      username: email,
      password: generatePassword(),
      options: {
        userAttributes: attributes,
      },
    });

    return await Promise.resolve(result);
  } catch (error) {
    return await Promise.reject(error);
  }
}

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

@didemkkaslan didemkkaslan added the pending-triage Issue is pending triage label Feb 29, 2024
@danieljandey
Copy link

danieljandey commented Feb 29, 2024

@didemkkaslan From a quick glance it looks like I am having the same issue.

Check if your code works on any version between v6.0.0 and v6.0.9.

If it works we may be facing the same issue. As a temporary fix I added a small delay before the getCurrentUser() function:

await new Promise(r => setTimeout(r, 100));
// Attempt to retrieve the current authenticated user
await Auth.getCurrentUser()

@didemkkaslan
Copy link
Author

@danieljandey unfortunately lowering the version didn't fix it for me. I've also tried setTimouts with no luck. The error is thrown when confirmSignup runs.

  await confirmSignIn({
        challengeResponse: idToken,
  });

I think this code internally calls getCurrentUser

@cwomack cwomack added the Auth Related to Auth components/category label Feb 29, 2024
@cwomack cwomack self-assigned this Feb 29, 2024
@cwomack cwomack added the investigating This issue is being investigated label Mar 11, 2024
@israx
Copy link
Member

israx commented Mar 11, 2024

hello @didemkkaslan . Amplify will call getCurrentUser after a user has been successfully authenticated . However if getCurrentUser is not able to retrieve the auth tokens it will throw the UserUnAuthenticatedException.

Saying that, the main issue is due to Amplify not being able to set tokens in the storage mechanism. This can be due to a domain mismatch while using cookies.

@didemkkaslan
Copy link
Author

Hello @israx I've tried to create my own tokenProvider and credentialsProvider for this reason but this time I get Auth UserPool not configured error. Is below implementation is the way to go if I want to set auth tokens for also different domains ( in this case msteams.com ) Thanks for the help

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

const amplifyConfig = parseAmplifyConfig(amplifyconfig);

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

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`,
          },
          PlatformIntegrationRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_INTEGRATION_REST_API_ENDPOINT}`,
          },
          PlatformRestApi: {
            endpoint: `${process.env.NEXT_PUBLIC_PLATFORM_REST_API_ENDPOINT}`,
          },
        },
      },
    },
    {
      ssr: true,
      Auth: {
        tokenProvider: createUserPoolsTokenProvider(
          {
            ...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!,
            },
          },
          keyValueStorage,
        ),
        credentialsProvider: createAWSCredentialsAndIdentityIdProvider(
          {
            ...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!,
            },
          },
          keyValueStorage,
        ),
      },
      API: {
        REST: {
          headers: async () => ({
            Authorization: `Bearer ${await getAuthToken()}`,
          }),
        },
      },
    },
  );
}

@israx
Copy link
Member

israx commented Mar 11, 2024

can you override only the storage mechanism from the cognito token provider ? Something like

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

import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito';

const authConfig: ResourcesConfig['Auth'] = {
  Cognito: {
    userPoolId: 'your_user_pool_id',
    userPoolClientId: 'your_user_pool_client_id'
  }
};

Amplify.configure({
  Auth: authConfig
});

cognitoUserPoolsTokenProvider.setKeyValueStorage(keyValueStorage);

for more information you can review this docs: https://docs.amplify.aws/react/build-a-backend/auth/manage-user-session/#update-your-token-saving-mechanism

@didemkkaslan
Copy link
Author

I've tried it but still getting the same error. looks like tokens are not set for msteams
Screenshot 2024-03-11 at 23 38 26
Screenshot 2024-03-11 at 23 38 56

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 keyValueStorage = createKeyValueStorageFromCookieStorageAdapter({
  get(name) {
    const value = getCookie(name);
    return { name, value };
  },
  getAll() {
    const cookies = getCookies();
    return Object.keys(cookies).map((name) => ({ name, value: cookies[name] }));
  },
  set(name, value) {
    setCookie(name, value);
  },
  delete(name) {
    deleteCookie(name);
  },
});

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`,
          },
          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);
}

@israx
Copy link
Member

israx commented Mar 11, 2024

can you add the https://teams.microsoft.com domain into the cookies configuration ?

@didemkkaslan
Copy link
Author

Thank you @israx ✨ the problem is solved with the domain setting. For anyone encountering this issue I want to share the latest configuration that fixed my problem

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);
  },
});

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`,
          },
          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);
}

@cwomack
Copy link
Member

cwomack commented Mar 12, 2024

@didemkkaslan, sounds like @israx's helpful replies helped get things unblocked here! Are there any lingering issues with this at this time?

@cwomack cwomack added question General question pending-response and removed investigating This issue is being investigated pending-triage Issue is pending triage labels Mar 12, 2024
@didemkkaslan
Copy link
Author

didemkkaslan commented Mar 12, 2024 via email

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 question General question
Projects
None yet
Development

No branches or pull requests

4 participants