Secure your data
Your website’s code contains the backend URL and the publishable key, so anyone who opens your site can call the Amplify backend data API with them. Neither value is a secret. You control what each request can read and change with grants and row-level security (RLS) policies in your PostgreSQL migrations.
A request with only the publishable key uses the anon role, and a signed-in user’s request uses authenticated. For more information about the roles, see API keys and roles. PostgreSQL checks two things for each request:
-
Grants – which roles can try an operation, such as
select, on a table. -
Policies – which rows the operation can read or change.
By default, anyone can sign up with an email address and a password, so authenticated means anyone who has an account, not only users that you approve. A policy that checks only the role exposes its rows to anyone who signs up. To turn off sign-up, see Email and password.
Write a table, its grants and its policies in the same migration. For more information about migrations, see Tables and migrations.
Grant access to a table
A new table has no grants to anon or authenticated, so data API requests to it fail with permission denied. In the table’s migration, grant each role only the operations that your policies cover:
grant select on public.notes to authenticated; -- add anon only if signed-out visitors read it grant insert, update, delete on public.notes to authenticated; -- add anon only for tables that signed-out visitors write to
Use bigint generated always as identity or uuid default gen_random_uuid() keys. An insert with a key that’s already taken fails, even when the caller can’t read the row that has it. If callers can set the key, they can use those failures to find out which rows exist. If your table uses another kind of key, grant only the columns that clients write: grant insert (body), update (body) on public.notes to authenticated;.
Turn on row-level security
RLS is on for every new table in public. Turn it on in the table’s migration anyway, so the migration doesn’t depend on that default:
alter table public.notes enable row level security;
anon and authenticated can’t read or write any row of a table that has RLS on and no policies. A read returns [] without an error, an update or delete changes 0 rows, and an insert fails with 409
WRITE_CONFLICT. None of these responses says that a policy is missing.
Warning: To fix missing rows, write a policy. Never turn off RLS or write using (true) on users' data: either one exposes every row through the data API.
Write policies
auth.uid() returns the signed-in user’s ID as text. The following migration creates the notes table with its grants and policies. Each user can read and write only their own notes:
create table public.notes ( id bigint generated always as identity primary key, owner_id text not null default auth.uid(), -- text, to match auth.uid() body text not null ); create index notes_owner_idx on public.notes (owner_id); alter table public.notes enable row level security; create policy "notes_select_own" on public.notes for select to authenticated using ((select auth.uid()) = owner_id); create policy "notes_insert_own" on public.notes for insert to authenticated with check ((select auth.uid()) = owner_id); create policy "notes_update_own" on public.notes for update to authenticated using ((select auth.uid()) = owner_id) with check ((select auth.uid()) = owner_id); create policy "notes_delete_own" on public.notes for delete to authenticated using ((select auth.uid()) = owner_id); grant select, insert, update, delete on public.notes to authenticated;
The example follows these rules:
-
Write one policy for each operation and role, and give it an owner check. If a policy has
to authenticatedand no owner check, every signed-in user can use that operation on every row. -
Write
(select auth.uid())in a policy, and index the owner column. PostgreSQL runsauth.uid()once per statement when you wrap it inselect. -
Make owner columns
text not null default auth.uid(). A policy that compares auuidcolumn withauth.uid()fails withoperator does not exist: uuid = text. Write plainauth.uid()in the default, because PostgreSQL doesn’t allow a subquery in aDEFAULT. -
Pair each
updatepolicy with aselectpolicy, and give it bothusingandwith check. An update changes only the rows that the caller can read through aselectpolicy. A user can move a row to another owner when theupdatepolicy has nowith check.
A role that can read a row through a policy can read every column of that row that the role has a grant on.
Before you trust auth.email() in a policy, also check (auth.jwt()->>'email_verified')::boolean.
Common policy patterns
Public read, owner write
Anyone can read the public rows of routines, and owners can also read their private rows. Only owners can write:
create policy "read_public_or_own" on public.routines for select to anon, authenticated using (is_public or owner_id = (select auth.uid())); -- insert, update and delete policies as in notes grant select on public.routines to anon, authenticated; grant insert, update, delete on public.routines to authenticated;
Admins from a table
Keep admins and other app roles in a table. You can’t add claims to a user’s token, and users can change their own name, so don’t use a token claim to identify an admin.
create table public.admins (user_id text primary key); alter table public.admins enable row level security; create policy "admins_see_self" on public.admins for select to authenticated using (user_id = (select auth.uid())); grant select on public.admins to authenticated; create policy "own_or_admin_select" on public.orders for select to authenticated using ( owner_id = (select auth.uid()) or exists (select 1 from public.admins a where a.user_id = (select auth.uid())) );
To make a user an admin in an environment, insert their ID after they sign up there. A migration runs in every environment, so it can’t add a user who exists in only one. Run the following commands. Replace rosie@example.com with the user’s email.
id=$(aws amplifygen3 backend user get --env production --email rosie@example.com --query Id --output text) aws amplifygen3 db query "insert into public.admins (user_id) values ('$id')" --env production
Members who see each other
To let the members of a list see each other, read the caller’s memberships through a security definer function in another schema. A policy on list_members that queries list_members itself fails with infinite recursion detected in policy. The following migration creates the function and the policy:
create schema private; create function private.my_list_ids() returns setof bigint language sql stable security definer set search_path = '' as $$ select list_id from public.list_members where user_id = (select auth.uid()) $$; grant usage on schema private to authenticated; grant execute on function private.my_list_ids() to authenticated; create policy "members_see_members" on public.list_members for select to authenticated using (list_id in (select private.my_list_ids()));
Public counts over private rows
To show totals or taken slots, keep the table’s policies owner-only. Return only the columns that everyone may see, such as slot_id, from a security definer function in public. Your app calls it with backend.rpc('taken_slots'). For more information, see Call database functions.
create function public.taken_slots() returns table (slot_id bigint) language sql stable security definer set search_path = '' as $$ select slot_id from public.bookings $$; grant execute on function public.taken_slots() to authenticated; -- add anon only for signed-out visitors
Create views with security_invoker
Create every view with security_invoker = true, so that PostgreSQL checks the caller against the policies on the view’s tables:
create view public.order_summaries with (security_invoker = true) as select o.id, o.total, c.name from public.orders o join public.customers c on c.id = o.customer_id;
If you leave the option out, the view still gets security_invoker. A view with security_invoker = false runs as its owner and returns every row that its query selects.
A materialized view has no security_invoker option. When you create or refresh it, it fills its rows with its owner’s access, so don’t grant a materialized view over users' data to anon or authenticated.
Use security definer functions safely
A security definer function runs as its owner, and RLS doesn’t apply to it.
Important: Never add security definer to get past permission denied. Fix the grant or the policy instead.
When you write a security definer function:
-
Put it in a schema of your own, such as
private, unless your app calls it. The data API serves only thepublicschema. -
Check
(select auth.uid())in its body, and return only what that caller may see. -
Give it
set search_path = '', and qualify every name with its schema. -
Any role with
executecan call a function inpublicat/rest/rpc/<name>. A new function has noexecutegrant toanonorauthenticated, so grant only the role that needs it.
Test your policies
The aws amplifygen3 db commands log in as amplify_admin. That role can read every row and can’t switch to another role, so a query from these commands doesn’t test your policies. Test each policy change through the data API: as the owner, as a second user, and signed out. To test policies on the local backend, see Develop locally.
In the following steps, you test the notes table in the preview environment. Run aws amplifygen3 backend info --env preview, and replace <backend-url> and <publishable-key> with the AMPLIFY_BACKEND_URL and AMPLIFY_BACKEND_PUBLISHABLE_KEY values that it lists.
-
Sign up users A and B, and get a token for each. A token lasts 15 minutes.
API=<backend-url>; KEY=<publishable-key> curl -s -X POST "$API/auth/sign-up/email" -H "apikey: $KEY" -H 'content-type: application/json' \ -d '{"email":"a@example.com","password":"correct horse battery","name":"A"}' curl -s -c jar-a -X POST "$API/auth/sign-in/email" -H "apikey: $KEY" -H 'content-type: application/json' \ -d '{"email":"a@example.com","password":"correct horse battery"}' JWT_A=$(curl -s -b jar-a -H "apikey: $KEY" "$API/auth/token" | jq -r '.token') # Repeat for b@example.com, with jar-b and JWT_B -
Insert a row as A, then read it as B and signed out:
ID=$(curl -s -X POST "$API/rest/notes" -H "apikey: $KEY" -H "Authorization: Bearer $JWT_A" \ -H 'content-type: application/json' -H 'Prefer: return=representation' -d '{"body":"hello"}' | jq -r '.[0].id') # the new row's id curl -s "$API/rest/notes?id=eq.$ID" -H "apikey: $KEY" -H "Authorization: Bearer $JWT_B" # [] curl -s "$API/rest/notes" -H "apikey: $KEY" # 401, code 42501The insert often returns an
idother than 1, because identity values aren’t reused, so keep theidthat it returns. An update by B changes 0 rows, and an insert by B with A’sowner_idfails with409. -
Delete the test row as A with
id=eq.$ID. Then delete each test user withaws amplifygen3 backend user delete --env preview --email <email> --yes.
Warning: Your tables hold real data. Delete each test row by its key, never with an unscoped delete from or truncate.
To write the test in TypeScript, use the client SDK with one client for each user. For more information, see the client SDK README
Audit your tables
Run the following commands to check a deployed database for RLS mistakes:
aws amplifygen3 db lint --env preview --level error aws amplifygen3 db lint --env preview --fail-on error # fails a CI job on any error
The command checks the public schema unless you pass --schema, such as --schema public,private. It reports these findings as errors: a table that anon or authenticated can query with RLS off (rls_disabled_in_public), a table that has policies but has RLS off, and a view that those roles can query and that isn’t security_invoker. Warnings include a write policy whose check is true, and a function without set search_path. With --fail-on error, the command exits with a non-zero status (255) on any error-level finding, including findings that --level hides.
Errors
| What you see | Cause | Fix |
|---|---|---|
|
|
No grant for the caller’s role |
Grant the operation in a migration |
|
|
The caller can’t read the rows through any policy, or |
Add the policy |
|
|
The new row fails a policy’s |
Check the owner value and the policy |
|
|
A |
Make the column |
|
|
A policy reads its own table |
Use a |
For other errors, see Data API errors.