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

Getting - Auth UserPool not configured. #5839

Closed
4 tasks done
vashu0804 opened this issue Sep 25, 2024 · 10 comments
Closed
4 tasks done

Getting - Auth UserPool not configured. #5839

vashu0804 opened this issue Sep 25, 2024 · 10 comments
Labels
Authenticator An issue or a feature-request for an Authenticator UI Component question General question

Comments

@vashu0804
Copy link

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

@github-actions github-actions bot added pending-triage Issue is pending triage pending-maintainer-response Issue is pending response from an Amplify UI maintainer labels Sep 25, 2024
@thaddmt
Copy link
Contributor

thaddmt commented Sep 25, 2024

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?

@thaddmt thaddmt added pending-response Authenticator An issue or a feature-request for an Authenticator UI Component question General question and removed pending-triage Issue is pending triage pending-maintainer-response Issue is pending response from an Amplify UI maintainer labels Sep 25, 2024
@vashu0804
Copy link
Author

vashu0804 commented Sep 26, 2024

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.

@github-actions github-actions bot added the pending-maintainer-response Issue is pending response from an Amplify UI maintainer label Sep 26, 2024
@vashu0804
Copy link
Author

vashu0804 commented Sep 27, 2024

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

@thaddmt
Copy link
Contributor

thaddmt commented Sep 30, 2024

@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

@thaddmt thaddmt removed the pending-maintainer-response Issue is pending response from an Amplify UI maintainer label Sep 30, 2024
@github-actions github-actions bot added the pending-maintainer-response Issue is pending response from an Amplify UI maintainer label Sep 30, 2024
@thaddmt thaddmt added being-investigated and removed pending-maintainer-response Issue is pending response from an Amplify UI maintainer labels Sep 30, 2024
@vashu0804
Copy link
Author

@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.

@github-actions github-actions bot added the pending-maintainer-response Issue is pending response from an Amplify UI maintainer label Oct 2, 2024
@vashu0804
Copy link
Author

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

@cwomack
Copy link
Member

cwomack commented Oct 7, 2024

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.

@cwomack cwomack added pending-community-response Issue is pending response from the issue requestor or other community members and removed pending-response pending-maintainer-response Issue is pending response from an Amplify UI maintainer labels Oct 7, 2024
@vashu0804
Copy link
Author

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.

@github-actions github-actions bot added pending-maintainer-response Issue is pending response from an Amplify UI maintainer and removed pending-community-response Issue is pending response from the issue requestor or other community members labels Oct 8, 2024
@cwomack
Copy link
Member

cwomack commented Oct 8, 2024

@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.

@cwomack cwomack added pending-community-response Issue is pending response from the issue requestor or other community members and removed pending-maintainer-response Issue is pending response from an Amplify UI maintainer labels Oct 8, 2024
@github-actions github-actions bot added pending-maintainer-response Issue is pending response from an Amplify UI maintainer and removed pending-community-response Issue is pending response from the issue requestor or other community members labels Oct 12, 2024
@vashu0804
Copy link
Author

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

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending response from an Amplify UI maintainer label Oct 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Authenticator An issue or a feature-request for an Authenticator UI Component question General question
Projects
None yet
Development

No branches or pull requests

3 participants