amazon-web-servicesaws-amplify

Amplify data schema with multiple authorization rules


I am trying to create an Amplify (Gen 2) application with a data model that has two objects: a public 'Log' and a private 'User'. However, I am unsure how to define this in the defineData object. How can I define both apiKey and userPool authorization modes?

const schema = a.schema({
  Log: a
    .model({
      content: a.string(),
      createdBy: a.string()
    })
    .authorization((allow) => [
      allow.publicApiKey().to(['read']),
      allow.owner(),
    ]),
  User: a
    .model({
      name: a.string(),
      bio: a.string()
    })
    .authorization((allow) => [allow.owner()])
});

export type Schema = ClientSchema<typeof schema>;

export const data = defineData({
  schema,
  authorizationModes: {
    // defaultAuthorizationMode: 'apiKey',
    defaultAuthorizationMode: 'userPool',
  },
});

Solution

  • I resolved this by creating a separate functional component to list all posts. Within this component, I set the authorization mode at the client level:

    const client = generateClient<Schema>(
      {authMode: 'apiKey',}
    )
    

    This way, my schema and defineData within amplify/data/resource.ts remain unchanged. Whenever I need to use the apiKey auth mode, this method can be followed again.