I’m using an AWS Lambda to authorize a GraphQL query, I want to use the authorization token to get the client information from Cognito, and use the sub in the user attributes to check if the user purchased a phone in my Record Table, but every time I call the method it returns "Unauthorized: Not Authorized to access getPhone on type Query".
Schema:
type Phone
@model
@auth(rules: [{ allow: owner }, { allow: custom, operations: [read] }]) {
id: ID!
title: String!
description: AWSJSON!
rating: Float
}
AWS Lambda:
exports.handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
const {
authorizationToken,
requestContext: { variables },
} = event;
try {
const cognitoClient = new CognitoIdentityProviderClient({});
const cognitoInput = {
AccessToken: authorizationToken,
};
const cognitoCommand = new GetUserCommand(cognitoInput);
const user = await cognitoClient.send(cognitoCommand);
const userId = user.UserAttributes.find((x) => x.Name == "sub").Value;
const dynamoClient = new DynamoDBClient({});
const dynamoInput = {
Key: {
id: {
S: userId,
},
},
TableName: "RecordTable",
};
const dynamoCommand = new GetItemCommand(dynamoInput);
const response = await dynamoClient.send(dynamoCommand);
const purchasedPhones = response.Item.purchasedPhones.L.map((x) => x.S);
return {
isAuthorized:
purchasedPhones.filter((x) => x == variables.id).length > 0,
resolverContext: {
userid: userId,
info: requestContext,
more_info: response,
},
ttlOverride: 300,
};
} catch (error) {
return error;
}
};
GraphQL method:
const phone = await client.graphql<GraphQLQuery<GetPhoneQuery>>({
query: getPhone,
authMode: "lambda",
authToken: "xxxxxxx...xxx",
variables: {
id,
},
});
I’m not quite sure what I’m missing here.
2
Answers
i think you have been missing some points. It looks like your trying to implement authorisation logic for a phone model using AWS AppSync and AWS Lambda.
Check the IAM roles and permissions
verify the authorisation token
Debugging and DynamoDB interaction
Error hadndling
GraphQL query execution
i hope this helps 😉
That error is usually due to the denied fields in the return object for the lambda authoriser. deniedFields is an array that should contain all the fields, mutations and queries you DON’T permit the user to make. In your case, the lambda authoriser authorised the request but did not allow the specific request you made, I assume because you are not returning a deniedFields array – https://aws.amazon.com/blogs/mobile/appsync-lambda-auth/.
Return an empty deniedFields array for example and it will work. The whole point of the deniedFeilds is to give you fine-grained control over what each user can see.
Also, I would review the Cognito API quotas if you will call Cognito APIs in the lambda authoriser especially if you are only caching the response for 5 minutes.