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;
我正在尝试从用户那里获取电子邮件属性。登录后,我收到此错误: “获取用户属性时出错 NotAuthorizedException:访问令牌没有所需的范围”
在配置 AWS Amplify 以及 Cognito 应用程序客户端时,我已经将范围设置为包括“openid”和“email”。我可以成功登录,但无法检索电子邮件。我该如何解决这个问题?
我在这里将范围设置为“openid”和“email”。 (以及在应用程序客户端上)
// 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",
},
},
});
缺少“aws.cognito.signin.user.admin”,导致对 cognito 的 API 调用失败。