Funk Soul Ninja
Funk Soul Ninja

Reputation: 2183

Using AWS AppSync (with amplify), how does one allow authenticated users read-only access, but only allow mutations for object owners?

I'm using Cognito User Pools as the default authentication method. I'm also using iam for my lambda backend. I'm using an aws appsync client in the lambda function for some custom resolvers.

let's assume I have a User object type that fundamentally looks like this:

type User {
  id: ID!
  displayName: String!
}

What I want to be able to do:

  1. Allow full read/write access for the object owner.
  2. Allow the lambda function (with iam) full read/write access.
  3. Allow read-only access for users who are authenticated through cognito user pools, but are not the owner of the object.

I've been picking and prodding with the @auth directive attempting to get the results I'm looking for but nothing has been able to work. I've looked at the documentation at AWS GraphQL Transform Docs and I seem to be a bit confused.

Here's what I've tried:

type User
  @model
  @auth(rules: [
    { allow: owner, operations: [create, update, delete] }
    { allow: private, provider: iam, operations: [update, delete] }
  ]) {
  id: ID!
  displayName: String!
}

To my understanding, by removing read from the operations list in the @auth directive removes the check on get and list queries. What am I doing wrong? How do I achieved my desired results?

EDIT: To clarify, I've already enabled multiple authorization types. (cognito user pools by default and iam for the lambda resolvers). My question is: How do I use the @auth directive to get the intended results?

Upvotes: 1

Views: 1675

Answers (2)

Alex
Alex

Reputation: 3991

AuthProvider { apiKey iam oidc userPools }


So, I hope this can help you(its worked for me :-))

type User @model @auth(rules:  [
      { allow: owner ,operations:  [create, update, delete]},
      { allow: private, provider: iam, operations: [read, update, delete] }
      { allow: private, provider: userPools, operations: [read] }
    ]) {
  id: ID!
  name: String!
}

Upvotes: 3

parkerfath
parkerfath

Reputation: 1649

To enable both IAM and Cognito, you'll need to follow the instructions on using multiple authorization types: https://aws.amazon.com/blogs/mobile/using-multiple-authorization-types-with-aws-appsync-graphql-apis/

E.g. specifying @aws_iam or @aws_cognito_user_pools on the respective fields

For your use case, you'll probably then also need to add some code in your resolvers to control which users can perform which actions, as described in: https://docs.aws.amazon.com/appsync/latest/devguide/security-authorization-use-cases.html

E.g. along the lines of #if($context.result["Owner"] == $context.identity.username)

If you're looking to do this purely through the Amplify CLI, this person seems to have worked through a very similar problem: https://github.com/aws-amplify/amplify-cli/issues/2694

Upvotes: 0

Related Questions