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

Authentication Redirect Loop with Amplify Cognito in Next.js (Next 15.4.1, Amplify 5.3.26) #14203

Open
3 tasks done
rushicruk opened this issue Feb 11, 2025 · 6 comments
Open
3 tasks done
Labels
Next.js pending-community-response Issue is pending a response from the author or community. question General question SSR Issues related to Server Side Rendering V5

Comments

@rushicruk
Copy link

rushicruk commented Feb 11, 2025

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify APIs

GraphQL API

Amplify Version

v5

Amplify Categories

auth

Backend

None

Environment information

# Put output below this line


Describe the bug

I'm using SSO signin for our admin console authentication. After successful authentication via Cognito, the user is unexpectedly redirected back to the sign-in page. This occurs despite receiving a valid authorisation code and no explicit errors in the console. I'm currently migrating CRA to Nextjs. Same code works in React.

Additional Context:

  • The Auth.currentAuthenticatedUser() call in getUser() appears to fail silently after the redirect.
  • No errors in browser console/network tab during the flow.
  • Cognito app client settings include correct callback URLs.
  • Issue occurs in local/PR development environments.
  • Token storage mechanism (localStorage vs cookies) may be relevant due to SSR.

Troubleshooting Attempted:

  • Verified Cognito domain/app client configuration.

Expected behavior

After successful authentication, the user should remain authenticated and not be redirected to the sign-in page and navigate me to respective page.

Reproduction steps

nA

Code Snippet

"use client";
import { useCallback, useEffect, useState } from "react";
import { Auth } from "aws-amplify";
import { CognitoUser } from "amazon-cognito-identity-js";

export const useAuth = () => {
  const [user, setUser] = useState<CognitoUser>();
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isAuthorized, setIsAuthorized] = useState(false);

  const getUser = useCallback(async () => {
    if (process.env.NEXT_PUBLIC_DISABLE_AUTH === "true") {
      setIsAuthenticated(true);
      setIsAuthorized(true);
    } else {
      try {
        const authUser: CognitoUser =
          (await Auth.currentAuthenticatedUser()) as CognitoUser;
        if (authUser) {
          setUser(authUser);
          setIsAuthenticated(true);
          setIsAuthorized(
            !!(
              authUser.getSignInUserSession()?.getAccessToken().payload[
                "cognito:groups"
              ] as string[]
            )?.includes("admin_groups")
          );
        } else {
          setIsAuthenticated(false);
        }
      } catch (e) {
        setIsAuthenticated(false);
      }
    }
    setIsLoading(false);
  }, []);

  useEffect((): void => {
    getUser();
  }, [getUser]);

  const login =
    process.env.NEXT_PUBLIC_DISABLE_AUTH === "true"
      ? () => Promise.resolve()
      : () => Auth.federatedSignIn();

  return {
    user: user?.getSignInUserSession(),
    isAuthenticated,
    isAuthorized,
    logout: () => Auth.signOut(),
    login,
    isLoading,
  };
};

export default useAuth;

Log output

// Put your logs below this line


aws-exports.js

No response

Manual configuration

{
      aws_project_region: process.env.NEXT_PUBLIC_REGION,
      aws_user_pools_id: config.userPoolId,
      aws_user_pools_web_client_id: config.userPoolClientId,
      oauth: {
        domain: config.userPoolDomain,
        redirectSignIn: `${config.url}/admin`,
        redirectSignOut: config.url,
        responseType: "code",
      },
      API: {
        aws_appsync_graphqlEndpoint: config.apiGraphQlEndpoint,
        aws_appsync_region: process.env.NEXT_PUBLIC_REGION,
        aws_appsync_authenticationType: "API_KEY",
        aws_appsync_apiKey: config.publicApiKey,
      },
      ssr: true,
}

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

@github-actions github-actions bot added pending-triage Issue is pending triage pending-maintainer-response Issue is pending a response from the Amplify team. labels Feb 11, 2025
@HuiSF HuiSF added SSR Issues related to Server Side Rendering Next.js V5 labels Feb 11, 2025
@ashwinkumar6
Copy link
Member

Hi @rushicruk,
Thanks for raising the issue we'll discussion with the team and get back

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Feb 12, 2025
@ashwinkumar6
Copy link
Member

Hi @rushicruk,
Could you try listening to the Auth hub events to check what events are fired when you're redirected back to your app from the cognito hostedUI.

Additionally, could you also double check Auth.currentAuthenticatedUser API is called only after the Auth Hub's cognitoHostedUI event is fired. (i.e double check if there's no race condition here)

@ashika112 ashika112 added question General question and removed pending-triage Issue is pending triage labels Feb 13, 2025
@rushicruk
Copy link
Author

Hello,
I've added logs as per above and found below. I don't know what argument is invalid. Perfectly works in React 18 (CRA)

TypeError: argument name is invalid
    at Object.serialize (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/universal-cookie/esm/index.mjs:203:12)
    at Cookies.remove (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/universal-cookie/esm/index.mjs:470:45)
    at UniversalStorage.removeUniversalItem (webpack-internal:///../../node_modules/.pnpm/@[email protected][email protected]_@[email protected]_@[email protected]_@bab_tjfpt3qftahifdh2p6r23ss6jm/node_modules/@aws-amplify/core/lib-esm/UniversalStorage/index.js:69:22)
    at UniversalStorage.removeItem (webpack-internal:///../../node_modules/.pnpm/@[email protected][email protected]_@[email protected]_@[email protected]_@bab_tjfpt3qftahifdh2p6r23ss6jm/node_modules/@aws-amplify/core/lib-esm/UniversalStorage/index.js:63:14)
    at CognitoUser.clearCachedUserData (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/amazon-cognito-identity-js/es/CognitoUser.js:1246:18)
    at CognitoUser.setSignInUserSession (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/amazon-cognito-identity-js/es/CognitoUser.js:109:10)
    at AuthClass.eval (webpack-internal:///../../node_modules/.pnpm/@[email protected][email protected]_@[email protected]_@[email protected]_@bab_rjqh4y2bkmsitukkt2n4gyj3ga/node_modules/@aws-amplify/auth/lib-esm/Auth.js:2316:37)
    at step (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.js:126:23)
    at Object.eval [as next] (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.js:107:53)
    at fulfilled (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.js:97:58) 'user sign in failed'


undefined 'Cognito Hosted UI sign in failed'


 TypeError: argument name is invalid
    at Object.serialize (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/universal-cookie/esm/index.mjs:203:12)
    at Cookies.remove (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/universal-cookie/esm/index.mjs:470:45)
    at UniversalStorage.removeUniversalItem (webpack-internal:///../../node_modules/.pnpm/@[email protected][email protected]_@[email protected]_@[email protected]_@bab_tjfpt3qftahifdh2p6r23ss6jm/node_modules/@aws-amplify/core/lib-esm/UniversalStorage/index.js:69:22)
    at UniversalStorage.removeItem (webpack-internal:///../../node_modules/.pnpm/@[email protected][email protected]_@[email protected]_@[email protected]_@bab_tjfpt3qftahifdh2p6r23ss6jm/node_modules/@aws-amplify/core/lib-esm/UniversalStorage/index.js:63:14)
    at CognitoUser.clearCachedUserData (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/amazon-cognito-identity-js/es/CognitoUser.js:1246:18)
    at CognitoUser.setSignInUserSession (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/amazon-cognito-identity-js/es/CognitoUser.js:109:10)
    at AuthClass.eval (webpack-internal:///../../node_modules/.pnpm/@[email protected][email protected]_@[email protected]_@[email protected]_@bab_rjqh4y2bkmsitukkt2n4gyj3ga/node_modules/@aws-amplify/auth/lib-esm/Auth.js:2316:37)
    at step (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.js:126:23)
    at Object.eval [as next] (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.js:107:53)
    at fulfilled (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.js:97:58)
 'custom state failure'

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Feb 13, 2025
@rushicruk
Copy link
Author

rushicruk commented Feb 13, 2025

Hello,
after lot of research found that assigning cookieStorage in Amplify config fixed the issue

cookieStorage: {
        domain: config.url.replace(/^https?:\/\//, "").split("/")[0],
        path: "/",
        expires: 7,
        secure: NODE_ENV === "development" ? false : true,
        sameSite: "lax",
      },

@HuiSF
Copy link
Member

HuiSF commented Feb 13, 2025

Hi @rushicruk a side note, since your working with Next.js 15+, we recommend you to use Amplify JS v6 along with the @aws-amplify/adapter-nextjs package (see this documentation for more details) which has a better support for newer version of Next.js. At this moment, we are not introducing any new feature to adapt new version of Next.js to v5.

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Feb 13, 2025
@HuiSF
Copy link
Member

HuiSF commented Feb 13, 2025

Regarding the error

TypeError: argument name is invalid

It's thrown from the underlying dependency universal-cookie. Looking at its source code it's thrown when the cookie name doesn't conform this regular expiression:

/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

The workaround you pasted simply replaces the usage of universal-cookie so I suspect something might be wrong with the generated cookie name. Could you check what's value format of the username of the account you used for create this error? Or better could add a break point here:

at Cookies.remove (webpack-internal:///../../node_modules/.pnpm/[email protected]/node_modules/universal-cookie/esm/index.mjs:470:45)

so inspect the passed in cookie name?

@ashika112 ashika112 added the pending-community-response Issue is pending a response from the author or community. label Feb 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Next.js pending-community-response Issue is pending a response from the author or community. question General question SSR Issues related to Server Side Rendering V5
Projects
None yet
Development

No branches or pull requests

4 participants