React 中 userPool 的 AWS AppSync 错误 401,但 AppSync 控制台中没有错误

AWS AppSync error 401 with userPool in React, but no error in AppSync console

我收到一个奇怪的错误,仅当我尝试 运行 我的 React 应用程序中的查询时,但它使用 AppSync 查询控制台工作。 userPool 配置正确,我以我的池中在 AppSync 控制台中工作的同一用户身份登录到 React 应用程序。

我像这样将我的整个应用程序包装在 withAuthenticator 中:

import aws_config from './aws-exports';
import Amplify, { API } from 'aws-amplify';
import { withAuthenticator } from '@aws-amplify/ui-react';
import { Auth } from '@aws-amplify/auth'
API.configure(aws_config);
Amplify.configure(aws_config);
Auth.configure(aws_config);
class App extends Component {
    ...
}
const AppWithAuth = withAuthenticator(App, true);
export default () => (
  <div className="auth-container">
    <AppWithAuth />
  </div>
);

我正在尝试加载的页面 运行 是一个简单的列表查询,我登录到控制台进行调试。我还预先添加了一个身份验证检查,看起来身份验证是正确的:

async componentDidMount() {
    console.log(await API.Auth.currentAuthenticatedUser())
    console.log(await API.graphql(graphqlOperation(listFacebookLogs, {limit: 10})))
}

我上面的控制台输出是(编辑删除识别信息):

CognitoUser {username: "james", pool: CognitoUserPool, Session: null, client: Client, signInUserSession: CognitoUserSession, …}
POST https://abcd1234.appsync-api.us-east-2.amazonaws.com/graphql 401

The response payload is: {"errors" : [ {"errorType" : "UnauthorizedException", "message" : "Permission denied" } ]}

现在,如果我以在 AppSync 控制台中使用的相同 userPool 身份登录,查询就会通过,并且我的列表会返回到查询中。这让我相信身份验证设置正确,因为 userPool 登录在 AppSync 控制台中工作。因此,确认 withAuthenticator 登录在我的查询之前打印得很好,应该表明我得到了正确的授权,对吧?

我已确保我的架构已通过身份验证正确设置,我的本地放大 cli 已同步,aws-exports 与云匹配,等等。 非常感谢任何帮助!

在 AppSync 查询控制台中传递查询:

通过我的 React 应用程序在浏览器中查询失败:(你可以看到我在查询之前打印了正确的经过身份验证的用户)

查询:

我的 aws-exports 用于身份验证:

架构:

哇!弄清楚了。当您创建 Cognito 组时,它会创建一个新的 IAM 角色(无价值的角色)。所以我必须做的是编辑每个组并将角色设置为 AppSync 使用的 Auth 角色,而不是使用它创建的角色。我想,或者,我可以进入 IAM 和 link 组角色到我想要的 appsync 主持身份。这将允许我将不同的组限制为 CRUD。

组使用 IAM 角色控制对 AWS 资源的权限。任何时候将 Cognito 组分配给任何用户,我们都需要确保分配给该组的角色具有访问资源所需的权限。

这是参考文章,以备不时之需 https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html