无法使用 Supabase 中经过身份验证的角色策略插入 table

Cannot insert to table with authenticated role policy in Supabase

我正在尝试在启用了 RLS 并添加了 Enable insert for authenticated users only 策略的 table 中插入一行。 不幸的是,即使我正确登录,我也无法插入。

重现步骤:

  1. 创建提交table
create table submission (
  stuff text
);
  1. 启用 RLS
alter table submissions
  enable row level security
  1. 添加策略
CREATE POLICY "Enable insert for authenticated users only" ON public.submissions FOR INSERT WITH CHECK (auth.role() = 'authenticated');
  1. 在客户端上,我使用魔术链接登录(对象已正确添加到本地存储中,所以我知道我已登录)

  2. 我尝试插入

const { data, error } = await supabase
 .from("submissions")
 .insert({ stuff: 'hello' });

http 调用中存在 Authorization Bearer <Jwt>

  1. 但是我得到了错误
{
  "hint":null,
  "message":"new row violates row-level security policy for table \"submissions\"",
  "code":"42501",
  "details":null
}

我做错了什么?

我发现哪里出了问题。

问题是,supabase.insert returns 我们刚刚插入的行的默认行为,换句话说,它从 table 中选择(读取)它。由于我没有添加策略来读取 table,它失败了。

所以两个解决方案:

  1. 添加一个新策略可以 SELECT 从那个 table
  2. { returning: "minimal" } 添加到 supabase.insert,这样它就不会将行发回

是的——我 运行 第一次尝试添加只允许 INSERT 而不允许 SELECT 的 RLS 策略(让用户将信息记录到 table.)

我们已经讨论过将 { returning: "minimal" } 作为插入、更新和删除的默认设置,但我认为这不会发生。

这只是需要注意的事情(它在文档中,但很容易错过。)