Supabase with JWT auth from Python client doesn't work with RLS

94 views Asked by At

I have a problem with Supabase that is related to RLS.

In my Python backend, I set up the supabase client and get the user based on the JWT jwt passed by the frontend:

user = supabase.auth.get_user(jwt)
user_id = user.dict().get("user").get("id")

response = (
    supabase
    .table("users")
    .update({"credits": 10})
    .eq("user_id", user_id)
    .execute()
)

Without RLS, this works fine, updating the row successfully.

However, with the following RLS rules, nothing is modified and 0 rows are returned:

create policy "Everybody can select users."
    on users for select
    using ( true );

create policy "Users can update own user."
    on users for update
    using ( auth.uid() = user_id );

What am I doing wrong? Obviously I have to use some RLS ruleā€¦ But I guess the authentication check ( auth.uid() = user_id ) doesn't match up when using the JWT.

I think I need to pass the JWT to the supabase client as well, so it's included in all requests, but I don't know how!

Help!?

1

There are 1 answers

0
shredEngineer On BEST ANSWER

OK, I solved it like this:

# Update this with the data of a currently logged in user
access_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..."
refresh_token = "xxxxxxxxxxxxxxxxxxxxxx"

supabase: Client = create_client(
    os.environ.get("NEXT_PUBLIC_SUPABASE_URL"),
    os.environ.get("NEXT_PUBLIC_SUPABASE_ANON_KEY"),
)
supabase.auth.set_session(access_token=access_token, refresh_token=refresh_token)

However, I now suggest just using the supabase service role key on the backend:

supabase: Client = create_client(
    os.environ.get("NEXT_PUBLIC_SUPABASE_URL"),
    os.environ.get("SUPABASE_SERVICE_ROLE_KEY"),
)

You can then still verify that your user is logged in by running:

supabase.auth.get_user(access_token)

Which will make a request to supabase and return the user data.