无法从AWS cognito获取用户电子邮件ID

问题描述 投票:0回答:1

我遇到一个问题,使用 AWS cognito 完成身份验证后,我根本没有获取用户电子邮件 ID。

// import './App.css';
import React from 'react';
import {Amplify} from 'aws-amplify';
import awsmobile from './aws-exports';
import {withAuthenticator, Authenticator} from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css'
// import SignIn from './SignIn';

Amplify.configure(awsmobile)

// console.log(Authenticator.SignIn())
// console.log(aoihe)


function App() {
  return (
    <Authenticator>
    {({ signOut, user }) => (
      <div className="App">
      {/* <SignIn SignInComponent={Authenticator.SignIn} /> */}
        <p>
          Hey {user.username}, welcome to my channel, with auth!
        </p>
        {user.attributes && user.attributes.email ?
        <h2>{user.attributes.email}</h2> :
        <h2>Email not available</h2>  
      }
        {/* You can enable this after ensuring user attributes are available */}
        {/* <h2>{user.attributes?.email || "Email not available"}</h2> */}
        <button onClick={signOut}>Sign Out</button>
      </div>
    )}
  </Authenticator>
  );
}

export default withAuthenticator(App);

首先,我无法从“aws-amplify”导入身份验证。身份验证在“aws-amplify”中根本不可用,仅 Amplify 可用。例如,从 'aws-amplify' 导入 {Amplify};那么,我可以使用什么模块/库来获取用户电子邮件 ID 和用户电话号码,而不是 Auth。提前非常感谢您提供解决方案。

reactjs amazon-web-services authentication amazon-cognito
1个回答
0
投票

您可以直接使用 AWS Amplify 的 Authenticator 组件获取用户电子邮件和电话号码属性,该组件已包含在代码中。看来您访问 user.attributes.email 的方向正确。以下是解决问题的方法:

1。导入授权: 如果您无法从“aws-amplify”导入身份验证,则您的 AWS Amplify 版本可能缺少某些依赖项,或者安装可能不完整。您可以尝试重新安装 Amplify 及其 UI 组件:

npm install aws-amplify @aws-amplify/ui-react

2。检索用户电子邮件和电话: 由于您已经在使用身份验证器组件,因此您不一定需要身份验证来获取用户的电子邮件或电话号码。身份验证器中提供的用户对象已包含必要的属性,包括电子邮件和电话号码(如果可用)。

3.检查属性是否存在: 确保 Cognito 用户池配置为返回电子邮件和电话号码作为属性。您可以在 AWS Cognito 控制台的属性和应用程序客户端设置下仔细检查这一点。

这是组件的更新版本,其中包括电子邮件和电话号码:

function App() {
  return (
    <Authenticator>
      {({ signOut, user }) => (
        <div className="App">
          <p>Hey {user.username}, welcome to my channel, with auth!</p>
          {user.attributes && user.attributes.email ? (
            <h2>Email: {user.attributes.email}</h2>
          ) : (
            <h2>Email not available</h2>
          )}
          {user.attributes && user.attributes.phone_number ? (
            <h2>Phone: {user.attributes.phone_number}</h2>
          ) : (
            <h2>Phone number not available</h2>
          )}
          <button onClick={signOut}>Sign Out</button>
        </div>
      )}
    </Authenticator>
  );
}

export default withAuthenticator(App);

只要用户在注册期间提供了电子邮件和电话号码,就应该可以使用。如果它们丢失,可能是由于 Cognito 设置所致。

此外,如果您想稍后手动管理用户属性,请在重新安装软件包后重新尝试导入 Auth:

import { Auth } from 'aws-amplify';

如果有帮助请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.