javascriptamazon-cognitoaws-amplifyaccess-tokenawscognitotoken

Getting AWS cognito attributes


import { useState, useEffect } from "react";
import { fetchUserAttributes } from "aws-amplify/auth";
import { useNavigate } from "react-router-dom"; // Add react-router-dom for navigation

function App(props) {  // No need for WithAuthenticatorProps here in JavaScript
  const [email, setEmail] = useState(""); // Email state
  const [userGroups, setUserGroups] = useState([]); // Explicitly declare as empty array
  const navigate = useNavigate(); // Hook for navigation

  useEffect(() => {
    // Fetch user attributes, including groups
    fetchUserAttributes().then((userAttrs) => {
      setEmail(userAttrs.email || "");
    })    .catch((error) => {
      console.error("Error fetching user attributes", error);
    });;
  }, [navigate]);

  return (
    <>
      <p>Hello {email}</p>
      <p>
        You can <button onClick={props.signOut}>logout</button>
      </p>
    </>
  );
}

export default App;

I am trying to get the email attribute from the user. Upon logging in, I get this error: "Error fetching user attributes NotAuthorizedException: Access Token does not have required scopes"

I have already set the scope to include "openid" and "email" when configuring AWS Amplify as well as on the Cognito App Client side. I can log in successfully but cannot retrieve the email. How can I fix this?

I set the scopes to "openid" and "email" here. (and on the App Client)

// Configure AWS Amplify
Amplify.configure({
  Auth: {
    Cognito: {
      loginWith: {
        oauth: {
          redirectSignIn: ["http://localhost:5173"],
          redirectSignOut: ["http://localhost:5173"],
          domain: "us-east-domain",
          providers: ["Google"],
          scopes: ["openid", "email"],
          responseType: "code",
        },
      },
      userPoolId: "userpoolid",
      userPoolClientId: "userpoolclientid",
    },
  },
});

Solution

  • Missing "aws.cognito.signin.user.admin", causing the API call to cognito to fail.