所以我认为这个问题来自于我不太理解 AWS cognito 用户池和 graphql 模式中的身份验证规则之间的关系。
当我运行下面的代码时,我收到消息“未授权访问 User 类型上的 createUser”。
import React from 'react';
import { Auth, API, graphqlOperation } from 'aws-amplify';
import { withAuthenticator } from "@aws-amplify/ui-react";
// This was created automatically from the schema by aws amplify
const CreateUser = /* GraphQL */ `
mutation CreateUser(
$input: CreateUserInput!
$condition: ModelUserConditionInput
) {
createUser(input: $input, condition: $condition) {
id
username
conversations {
items {
id
convoLinkUserId
convoLinkConversationId
createdAt
updatedAt
}
nextToken
}
messages {
items {
id
authorId
content
messageConversationId
createdAt
updatedAt
}
nextToken
}
createdAt
updatedAt
}
}
`;
async function signIn(username, password) {
try {
const user = await Auth.signIn(username, password);
const { attributes } = user;
console.log("User", attributes)
return user
} catch (error) {
console.log('error signing in', error);
}
}
async function createUser(id) {
// creating a new user in the dynamodb table
try {
const newUser = {input: {username: id, id}}
console.log("Creating new user", newUser)
await API.graphql(graphqlOperation(CreateUser, newUser))
} catch (err) {
console.log('Error creating user! :', err)
}
}
async function testApiCalls() {
await signIn("[email protected] /cdn-cgi/l/email-protection", "notarealpassword123") // runs successfully
await createUser("[email protected] /cdn-cgi/l/email-protection") // where the error happens
}
function App() {
testApiCalls()
return (
<div className="App">
Hello
</div>
);
}
export default withAuthenticator(App);
其他相关代码是我的index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Amplify, { Auth } from 'aws-amplify';
import AWSAppSyncClient from 'aws-appsync'
import aws_config from './aws-exports';
import { ApolloProvider } from '@apollo/client';
Amplify.configure(aws_config);
aws_config.graphql_headers = async () => { const currentSession = await Auth.currentSession(); return { Authorization: currentSession.getIdToken().getJwtToken() }; };
const client = new AWSAppSyncClient({
url: aws_config.aws_appsync_graphqlEndpoint,
region: aws_config.aws_appsync_region,
auth: {
type: aws_config.aws_appsync_authenticationType, // AMAZON_COGNITO_USER_POOLS
jwtToken: async () => (await Auth.currentSession()).idToken.jwtToken
}
});
const WithProvider = () => (
<ApolloProvider client={client}>
<App/>
</ApolloProvider>
)
ReactDOM.render(
<WithProvider/>,
document.getElementById('root')
);
以及 User 对象的架构定义:
type User
@model
@auth(rules: [{ allow: owner, ownerField: "id", queries: null }]) {
id: ID!
username: String!
conversations: [ConvoLink] @connection(name: "UserLinks")
messages: [Message] @connection(name: "UserMessages")
createdAt: String
updatedAt: String
}
最终,我正在尝试制作类似的东西example https://github.com/amazon-archives/aws-appsync-chat。我尝试阅读 aws amplify 文档,但无法正确理解身份验证如何影响 graphql 操作。