Public data access
The public authorization strategy grants everyone access to the API, which is protected behind the scenes with an API key. You can also override the authorization provider to use an unauthenticated IAM role from Cognito instead of an API key for public access.
Add public authorization rule using API key-based authentication
To grant everyone access, use the .public()
authorization strategy. Behind the scenes, the API will be protected with an API key.
const schema = a.schema({ Todo: a .model({ content: a.string(), }) .authorization(allow => [allow.publicApiKey()]),});
In your application, you can perform CRUD operations against the model by specifying the apiKey
auth mode.
try { final todo = Todo(content: 'My new todo'); final request = ModelMutations.create( todo, authorizationMode: APIAuthorizationType.apiKey, ); final createdTodo = await Amplify.API.mutations(request: request).response;
if (createdTodo == null) { safePrint('errors: ${response.errors}'); return; } safePrint('Mutation result: ${createdTodo.name}');
} on APIException catch (e) { safePrint('Failed to create todo', e);}
Add public authorization rule using Amazon Cognito identity pool's unauthenticated role
You can also override the authorization provider. In the example below, identityPool
is specified as the provider which allows you to use an "Unauthenticated Role" from the Cognito identity pool for public access instead of an API key. Your Auth resources defined in amplify/auth/resource.ts
generates scoped down IAM policies for the "Unauthenticated role" in the Cognito identity pool automatically.
const schema = a.schema({ Todo: a .model({ content: a.string(), }) .authorization(allow => [allow.guest()]),});
In your application, you can perform CRUD operations against the model using client.models.<model-name>
with the identityPool
auth mode.
import { generateClient } from 'aws-amplify/data';import type { Schema } from '../amplify/data/resource'; // Path to your backend resource definition
const client = generateClient<Schema>();
const { errors, data: newTodo } = await client.models.Todo.create( { content: 'My new todo', }, { authMode: 'identityPool', });
In your application, you can perform CRUD operations against the model with the iam
auth mode.
try { final todo = Todo(content: 'My new todo'); final request = ModelMutations.create( todo, authorizationMode: APIAuthorizationType.iam, ); final createdTodo = await Amplify.API.mutations(request: request).response;
if (createdTodo == null) { safePrint('errors: ${response.errors}'); return; } safePrint('Mutation result: ${createdTodo.name}');
} on APIException catch (e) { safePrint('Failed to create todo', e);}