aws-amplify / amplify-ui

Amplify UI is a collection of accessible, themeable, performant React (and more!) components that can connect directly to the cloud.
https://ui.docs.amplify.aws
Apache License 2.0
931 stars 297 forks source link

Getting - Auth UserPool not configured. #5839

Closed vashu0804 closed 1 month ago

vashu0804 commented 2 months ago

Before creating a new issue, please confirm:

On which framework/platform are you having an issue?

React

Which UI component?

Authenticator

How is your app built?

Vite

What browsers are you seeing the problem on?

Chrome, Firefox, Microsoft Edge, Safari

Which region are you seeing the problem in?

India, Mumbai

Please describe your bug.

I have a react project in which aws amplify is getting utilised now on clicking the login button with google i am getting Auth UserPool not configured on my local. Please suggest something incase anyone have incountered the similar issue previously.

What's the expected behaviour?

Ideally it should log me in the website home page on click the sign in with google button.

Help us reproduce the bug!

Sharing the code snipped below for your reference. Getting the error on my local system

Code Snippet

// Put your code below this line.
import { fetchAuthSession } from "aws-amplify/auth";

export const awsConfig = {
  Auth: {
    Cognito: {
      // region: import.meta.env.VITE_COGNITO_REGION,
      userPoolId: import.meta.env.VITE_COGNITO_USER_POOLS_ID,
      userPoolClientId: import.meta.env.VITE_COGNITO_WEB_CLIENT_ID,
      // signUpVerificationMethod: 'link',
      // storage: localStorage,
      // authenticationFlowType: 'ALLOW_REFRESH_TOKEN_AUTH',
      loginWith: {
        oauth: {
          domain: import.meta.env.VITE_OAUTH_DOMAIN_NAME,
          scopes: [
            "phone",
            "email",
            "profile",
            "openid",
            "aws.cognito.signin.user.admin",
          ],
          redirectSignIn: [import.meta.env.VITE_OAUTH_REDIRECT_SIGNIN_URL],
          redirectSignOut: [import.meta.env.VITE_OAUTH_REDIRECT_SIGNOUT_URL],
          responseType: "code",
        },
      },
    },
  },
};

export async function setCurrentSession() {
  try {
    const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {};
    const { username } = accessToken?.payload || {};
    const accessTokenString = accessToken?.toString() || "";
    const { name, email, picture } = idToken?.payload || {};
    setUserAttributes(
      username as string,
      name as string,
      email as string,
      picture as string,
      accessTokenString
    );
  } catch (err) {
    console.log(err);
  }
}

export const setUserAttributes = (id: string, name: string, email: string, profilePicture: string, accessToken: string) => {
  const userInfo = {
    id,
    name,
    email,
    profilePicture,
    accessToken,
  };
  localStorage.setItem('UserInfo', JSON.stringify(userInfo));
};

export const getUserAttributes = () => {
  return JSON.parse(localStorage.getItem('UserInfo') || '{}');
};

export async function refreshCurrentSession() {
  try {
    const userInfo = getUserAttributes();
    const { tokens } = await fetchAuthSession({ forceRefresh: true });
    const accessToken = tokens?.accessToken.toString() || "";

    setUserAttributes(
      userInfo?.id,
      userInfo?.name,
      userInfo?.email,
      userInfo?.profilePicture,
      accessToken
    );
  } catch (err) {
    console.log(err);
  }
}

//Have another file for fetchAuthSession

import { AuthSession, FetchAuthSessionOptions } from '../Auth/types';
/**
 * Fetch the auth session including the tokens and credentials if they are available. By default it
 * does not refresh the auth tokens or credentials if they are loaded in storage already. You can force a refresh
 * with `{ forceRefresh: true }` input.
 *
 * @param options - Options configuring the fetch behavior.
 * @throws {@link AuthError} - Throws error when session information cannot be refreshed.
 * @returns Promise<AuthSession>
 */
export declare const fetchAuthSession: (options?: FetchAuthSessionOptions) => Promise<AuthSession>;

Console log output

Screenshot 2024-09-25 at 2 27 31 PM

Additional information and screenshots

No response

thaddmt commented 2 months ago

Can you also post the code where you use the Authenticator? Usually when this error occurs if your Amplify configuration is not set up correctly. Can you also show where you use the awsConfig with Amplify.configure?

vashu0804 commented 2 months ago

Can you also post the code where you use the Authenticator? Usually when this error occurs if your Amplify configuration is not set up correctly. Can you also show where you use the awsConfig with Amplify.configure?

Sure sharing the entire files step by step: In Main.tsx

/* eslint-disable @typescript-eslint/ban-ts-comment */
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { Amplify } from "aws-amplify";
import { Authenticator } from "@aws-amplify/ui-react";
import { IntlProvider } from "react-intl";
import { flatten } from "flat";
import {
  QueryClient,
  QueryCache,
  MutationCache,
  QueryClientProvider,
} from "@tanstack/react-query";
// import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import enMessages from "./translations/en.json";
import { SnackbarProvider, SnackbarOrigin } from "notistack";
import { MuiThemeProvider } from "./styles/muiTheme.tsx";
import { GlobalContextProvider } from "./context/GlobalContext";
import App from "./App.tsx";
import "./styles/main.css";
import { awsConfig } from "./utils/auth";
import ErrorBoundary from "./components/Common/ErrorBoundary.tsx";

//@ts-ignore
Amplify.configure(awsConfig);

const localeConfig: Record<string, any> = {
  en: enMessages,
};

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error) => console.error(`Something went wrong: ${error}`),
  }),
  mutationCache: new MutationCache({
    onError: (error) => console.error(`Something went wrong: ${error}`),
  }),
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
    },
  },
});

const defaultSnackBarOrigin: SnackbarOrigin = {
  vertical: "top",
  horizontal: "center",
};

ReactDOM.createRoot(document.getElementById("root")!).render(
  <ErrorBoundary>
    <BrowserRouter>
      <MuiThemeProvider>
        {/* // Todo: Solve this */}
        {/* Default locale en is being used as a fallback due to missing locale data
      for undefined locale in React-intl */}
        <IntlProvider locale={"en"} messages={flatten(localeConfig.en)}>
          <GlobalContextProvider>
            <Authenticator.Provider>
              <QueryClientProvider client={queryClient}>
                {/* <ReactQueryDevtools initialIsOpen={false} /> */}
                <SnackbarProvider
                  maxSnack={3}
                  autoHideDuration={2000}
                  anchorOrigin={defaultSnackBarOrigin}
                >
                  <App />
                </SnackbarProvider>
              </QueryClientProvider>
            </Authenticator.Provider>
          </GlobalContextProvider>
        </IntlProvider>
      </MuiThemeProvider>
    </BrowserRouter>
  </ErrorBoundary>
);

In Login.tsx

import { Box } from "@mui/material";
import { useLocation, Navigate } from "react-router-dom";
import { Authenticator } from "@aws-amplify/ui-react";
import "@aws-amplify/ui-react/styles.css";
import { useAuthenticator } from "@aws-amplify/ui-react";
import LogoSvg from "../assets/logo.svg";
import { LoginWrapper, AuthWrapper } from "./LoginStyles";

interface LocationState {
  from?: {
    pathname?: string;
  };
}
const LoginPage = () => {
  const { authStatus } = useAuthenticator((context: any) => [context.user]);
  const location = useLocation();
  const locationState = location.state as LocationState;
  const from = locationState?.from?.pathname || "/";

  if (authStatus === "authenticated") return <Navigate replace to={from} />;

  return (
    <LoginWrapper>
      <Box sx={{ paddingTop: "20px" }}>
        <img
          className="logoIcon"
          src={LogoSvg}
          style={{ height: "50px", width: "200px" }}
        />
      </Box>
      <AuthWrapper>
        <Authenticator socialProviders={["google"]} />
        {/* <SignUpWrapper>
          <div>Don't have any account?</div>
          <Link to={"/signup"}>
            <Button
              sx={{
                textTransform: "none",
                margin: "auto",
                fontSize: "16px",
              }}
            >
              Register
            </Button>
          </Link>
        </SignUpWrapper> */}
      </AuthWrapper>
    </LoginWrapper>
  );
};
export default LoginPage;

In loginWithGoogle.tsx

import { useEffect } from "react";
import queryString from "query-string";
import { signInWithRedirect } from "aws-amplify/auth";
import { useAuthenticator } from "@aws-amplify/ui-react";
import { useNavigate } from "react-router-dom";

const LoginWithGooglePage = () => {
  const navigate = useNavigate();
  const { authStatus } = useAuthenticator((context: any) => [context.user]);
  const queryParams = queryString.parse(location.search);
  const hashParams = location.hash;
  const continueParam = queryParams["continue"] || "/home";

  useEffect(() => {
    if (authStatus === "authenticated") {
      navigate("/home");
    } else
      signInWithRedirect({
        provider: "Google",
        customState: `${continueParam}${hashParams}` as string,
      });
  }, [authStatus]);

  return <></>;
};

export default LoginWithGooglePage;

Have used it at few more places I hope this is good for your understanding.

vashu0804 commented 2 months ago

@thaddmt Have you got the chance to check this??

thaddmt commented 2 months ago

@vashu0804 are you able to verify that your awsConfig has a value for userPoolId: import.meta.env.VITE_COGNITO_USER_POOLS_ID,? In a minimal repro the only time I get the error with oauth google login is if i remove the userPoolId

vashu0804 commented 2 months ago

@thaddmt Yes, I have added the userPoolId in my evn config file and also I am getting the error while logging in with google just like you were having.

vashu0804 commented 2 months ago

@thaddmt Please tell me if you need to any other info, or want to connect on meet to discuss this.

cwomack commented 1 month ago

Hey, @vashu0804 👋. Just to make sure we can cross this off the list, can you double check that the Cognito resource ID's for User Pool and Identity Pool aligns to what is within your environment variables? Also, can you see if hard coding the ID's into the config call resolves the issue? Thanks.

vashu0804 commented 1 month ago

Hey @cwomack , I double checked the Pool ID's still facing the same issue, can you please help me more in this. I also tried hard coding the values and it is working then but getting undefined.

cwomack commented 1 month ago

@vashu0804, can you share what's in your package.json so we can see if there are any dependencies that might be causing issues with the Amplify singleton? Also going to reference the Troubleshooting section of the docs if they help as well.

vashu0804 commented 1 month ago

@cwomack thanks for your help. I changed the mui version from 5 to 6 and now it is working.