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.4k stars 2.11k forks source link

withSSRContext: SSR.Auth.currentAuthenticatedUser() returns the error 'The user is not authenticated' #11014

Closed Nubtehy closed 1 year ago

Nubtehy commented 1 year ago

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

``` # Put output below this line System: OS: Windows 10 10.0.19045 CPU: (8) x64 Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz Memory: 3.62 GB / 15.78 GB Binaries: Node: 14.15.3 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.15 - ~\AppData\Roaming\npm\yarn.CMD npm: 6.14.9 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Spartan (44.19041.1266.0), Chromium (110.0.1587.50) Internet Explorer: 11.0.19041.1566 npmPackages: @ampproject/toolbox-optimizer: undefined () @babel/core: undefined () @babel/runtime: 7.15.4 @edge-runtime/primitives: 2.0.0 @hapi/accept: undefined () @napi-rs/triples: undefined () @next/react-dev-overlay: undefined () @react-google-maps/api: ^2.13.1 => 2.13.1 @reduxjs/toolkit: ^1.8.6 => 1.8.6 @reduxjs/toolkit-query: 1.0.0 @reduxjs/toolkit-query-react: 1.0.0 @segment/ajv-human-errors: undefined () @svgr/webpack: ^6.5.1 => 6.5.1 @vercel/nft: undefined () acorn: undefined () amphtml-validator: undefined () anser: undefined () arg: undefined () assert: undefined () async-retry: undefined () async-sema: undefined () aws-amplify: ^4.3.30 => 4.3.39 axios: ^1.1.2 => 1.1.3 (0.26.0) babel-packages: undefined () babel-plugin-styled-components: ^2.0.7 => 2.0.7 babel-preset-next: ^1.4.0 => 1.4.0 body-scroll-lock: ^4.0.0-beta.0 => 4.0.0-beta.0 browserify-zlib: undefined () browserslist: undefined () buffer: undefined () bytes: undefined () chalk: undefined () ci-info: undefined () cli-select: undefined () comment-json: undefined () compression: undefined () conf: undefined () constants-browserify: undefined () content-disposition: undefined () content-type: undefined () cookie: undefined () cross-env: ^7.0.3 => 7.0.3 cross-spawn: undefined () crypto-browserify: undefined () css.escape: undefined () cssnano-simple: undefined () data-uri-to-buffer: undefined () date-fns: ^2.29.3 => 2.29.3 debug: undefined () devalue: undefined () domain-browser: undefined () edge-runtime: undefined () eslint: 8.25.0 => 8.25.0 eslint-config-next: ^13.1.2 => 13.1.2 events: undefined () find-cache-dir: undefined () find-up: undefined () formik: ^2.2.9 => 2.2.9 fresh: undefined () get-orientation: undefined () glob: undefined () gzip-size: undefined () http-proxy: undefined () https: ^1.0.0 => 1.0.0 https-browserify: undefined () husky: ^8.0.1 => 8.0.1 icss-utils: undefined () ignore-loader: undefined () image-size: undefined () is-animated: undefined () is-docker: undefined () is-wsl: undefined () jest-worker: undefined () js-cookie: ^3.0.1 => 3.0.1 (2.2.1) json5: undefined () jsonwebtoken: undefined () loader-utils: undefined () lodash.curry: undefined () lru-cache: undefined () micromatch: undefined () mini-css-extract-plugin: undefined () nanoid: ^4.0.0 => undefined (4.0.0, , 3.3.4) native-url: undefined () neo-async: undefined () next: ^13.1.2 => 13.1.2 next-absolute-url: ^1.2.2 => 1.2.2 next-base64: ^1.1.0 => 1.1.0 next-cookies: ^2.0.3 => 2.0.3 next-i18next: ^12.1.0 => 12.1.0 next-i18next-create-client: undefined () next-seo: ^5.5.0 => 5.6.0 node-fetch: undefined () node-html-parser: undefined () ora: undefined () os-browserify: undefined () p-limit: undefined () path-browserify: undefined () platform: undefined () 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: ^2.7.1 => 2.7.1 pretty-quick: ^3.1.3 => 3.1.3 process: undefined () prop-types: ^15.8.1 => 15.8.1 punycode: undefined () qs: ^6.11.0 => 6.11.0 querystring-es3: undefined () raw-body: undefined () react: ^18.2.0 => 18.2.0 (18.3.0-next-3ba7add60-20221201) react-day-picker: ^8.4.1 => 8.4.1 react-device-detect: ^2.2.2 => 2.2.2 react-dom: ^18.2.0 => 18.2.0 (18.3.0-next-3ba7add60-20221201) react-is: 18.2.0 react-redux: ^8.0.4 => 8.0.4 react-refresh: 0.12.0 react-select: ^5.6.0 => 5.6.1 react-server-dom-webpack: undefined () react-toast-notifications: ^2.5.1 => 2.5.1 react-toastify: ^9.1.1 => 9.1.1 redux: ^4.2.0 => 4.2.0 regenerator-runtime: 0.13.4 sass-loader: undefined () scheduler: undefined () schema-utils: undefined () semver: undefined () send: undefined () setimmediate: undefined () sharp: ^0.31.3 => 0.31.3 shell-quote: undefined () source-map: undefined () stacktrace-parser: undefined () stream-browserify: undefined () stream-http: undefined () string-hash: undefined () string_decoder: undefined () strip-ansi: undefined () styled-components: ^5.3.6 => 5.3.6 styled-components/macro: undefined () styled-components/native: undefined () styled-components/primitives: undefined () swiper: ^8.4.4 => 8.4.4 swiper_angular: 0.0.1 tar: undefined () terser: undefined () text-table: undefined () timers-browserify: undefined () tty-browserify: undefined () ua-parser-js: undefined () undici: undefined () unistore: undefined () util: undefined () vm-browserify: undefined () watchpack: undefined () web-vitals: undefined () webpack: undefined () webpack-sources: undefined () ws: undefined () yup: ^0.32.11 => 0.32.11 npmGlobalPackages: @babel/plugin-proposal-class-properties: 7.18.6 bindings: 1.5.0 corepack: 0.10.0 file-uri-to-path: 1.0.0 jest: 24.0.0 nan: 2.17.0 typescript: 4.6.2 weak-napi: 2.0.2 webpack: 5.38.1 ```

Describe the bug

I'm using Cognito Authentication with Amplify in a next.js. I have case when third party site open page in my application. I've configured amplify with cookieStorage config, beacause only ssr: true. dosen't provide all cookies that need withSSRContext. when I open private page from third party website, I got the error The user is not authenticated. But user is authenticated. All cookies for cognito are provided.

My flow:

export const withAuth = async (context, cb) => {

    try {
        const SSR = withSSRContext(context);
        await SSR.Auth.currentAuthenticatedUser();

        return cb();
    } catch (error) {
        return {
            redirect: {
                destination: "/login",
                permanent: false
            }
        };
    }
};
export const getServerSideProps = async context => {
    return withAuth(context, async () => {
        return {
            props: {
                ...(await serverSideTranslations(context.locale, ["common", "cookie"]))
            }
        };
    });
};

Expected behavior

when I open private page from third party website, I should see private page when my user is authenticated

Reproduction steps

Open private page with from third party website. Get the error The user is not authenticated

Code Snippet

// Put your code below this line.

Log output

```bash [DEBUG] 01:18.782 AuthClass - getting current authenticated user [DEBUG] 01:18.782 AuthClass - get current authenticated userpool user [DEBUG] 01:18.782 AuthClass - Failed to get the user session Error: Local storage is missing an ID Token, Please authenticate at CognitoUser.getSession (D:\cye-nextjs-frontend\app\node_modules\amazon-cognito-identity-js\lib\CognitoUser.js:1152:16) at AuthClass. (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:1492:34) at step (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:56:23) at Object.next (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:37:53) at D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:31:71 at new Promise () at __awaiter (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:27:12) at D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:1453:44 [DEBUG] 01:18.783 AuthClass - The user is not authenticated by the error Error: Local storage is missing an ID Token, Please authenticate at CognitoUser.getSession (D:\cye-nextjs-frontend\app\node_modules\amazon-cognito-identity-js\lib\CognitoUser.js:1152:16) at AuthClass. (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:1492:34) at step (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:56:23) at Object.next (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:37:53) at D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:31:71 at new Promise () at __awaiter (D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:27:12) at D:\cye-nextjs-frontend\app\node_modules\@aws-amplify\auth\lib\Auth.js:1453:44 The user is not authenticated error
### aws-exports.js

_No response_

### Manual configuration

```js
{
    Auth: {
        identityPoolId: "",
        region: publicRuntimeConfig.COGNITO_AWS_REGION,
        userPoolId: publicRuntimeConfig.COGNITO_USER_POOL,
        userPoolWebClientId: publicRuntimeConfig.CLIENT_ID,
        mandatorySignIn: false,
        signUpVerificationMethod: "code", 
        authenticationFlowType: "USER_PASSWORD_AUTH",
        clientMetadata: { myCustomKey: "myCustomValue" },
        oauth: {
            domain: "mycognitodomain",
            redirectSignIn: publicRuntimeConfig.REDIRECT_URL,
            redirectSignOut: publicRuntimeConfig.REDIRECT_URL,
            responseType: "code" 
        },
        cookieStorage: {
            domain: 'localhost',
        },
    }
}

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

image

CognitoUser.js

const keyPrefix = CognitoIdentityServiceProvider.${this.pool.getClientId()}.${ this.username }; const idTokenKey = ${keyPrefix}.idToken; //idTokenKey= CognitoIdentityServiceProvider.**pdhmiepo.nubtehy@gmail.com.idToken

but in store it looks like 'CognitoIdentityServiceProvider.**pdhmiepo.nubtehy%40gmail.com.idToken

store: [Object: null prototype] { 'CognitoIdentityServiceProvider.**pdhmiepo.nubtehy%40gmail.com.idToken':

this.username is returned from LastAuthUser and there it was saved without encodeURIComponent

When I use encodeURIComponent for userName here everything works correctly

cwomack commented 1 year ago

Hello, @Nubtehy 👋. Can you confirm that the user has been fully verified within the Cognito User Pool via the SMS or emailed verification code that's sent after signing up?

Nubtehy commented 1 year ago

Hi @cwomack! I can provide you video record for confirmation if it is needed

cwomack commented 1 year ago

@Nubtehy, that would be great! It sounds like the potential bug here is the LastAuthUser isn't being URI encoded and has a mismatch when you're trying to pass those cookies to the third party site. Is that what you're seeing or can show in the video recording?

Nubtehy commented 1 year ago

@cwomack yes, exactly. Record.

mctang719 commented 1 year ago

I am having the same issue. I haven't touched a page I implemented a month ago. Now I am getting the user is not authenticated when using SSR. however Auth.currentAuthenticatedUser() on the client side is working just fine.

cwomack commented 1 year ago

@Nubtehy, any chance you could unarchive that video or post it again? It won't play any longer. I'd be happy to download it and save it if you wanted to it only be available short term!

Apologies I didn't do that sooner.

Nubtehy commented 1 year ago

@cwomack I uploaded it to the google drive, is it work for you? Link

cwomack commented 1 year ago

Awesome, thank you @Nubtehy!

cwomack commented 1 year ago

Related to #7684

cwomack commented 1 year ago

@Nubtehy after reviewing this further, it looks close enough to #7684 to call it a duplicate. As such, I'll close this down since the other issue is already in progress and leave a comment referencing your recording of the bug in action.

Greatly appreciate you providing that, and please follow the other issue for progress and updates on a fix!