Skip to content

Create a client with Auth context of a user #420

Closed
@vlebert

Description

@vlebert

Hi everyone

Is your feature request related to a problem? Please describe.

I am trying to write python cloud function (instead of supabase edge function). I wan't to get caller's identity do proceed database read/write with his RLS context.
In JS, this is possible as described in the documentation.

https://supabase.com/docs/guides/functions/auth

import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

serve(async (req: Request) => {
  try {
    // Create a Supabase client with the Auth context of the logged in user.
    const supabaseClient = createClient(
      // Supabase API URL - env var exported by default.
      Deno.env.get('SUPABASE_URL') ?? '',
      // Supabase API ANON KEY - env var exported by default.
      Deno.env.get('SUPABASE_ANON_KEY') ?? '',
      // Create client with Auth context of the user that called the function.
      // This way your row-level-security (RLS) policies are applied.
      { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
    )

With Python client, I couldn't reproduce. I tried:

supa_client = create_client("https://****.supabase.co",
                            "***anon_api_key***",
                            ClientOptions().replace(headers={"authorization":"Bearer ***user_session_token***"
}))

I also tried

supa_client = create_client("https://****.supabase.co",
                            "***anon_api_key***",
}))
supa_client.auth.set_session("***user_session_token***","")

None of this works. After studying the code a bit, I think this may be the problem:

https://github.com/supabase-community/supabase-py/blob/2bba842449ccd0b5f933198c343f54c5a67db7ed/supabase/client.py#L61

https://github.com/supabase-community/supabase-py/blob/2bba842449ccd0b5f933198c343f54c5a67db7ed/supabase/client.py#L208

Authorization token is always overwritten with anon API KEY

options.headers.update(self._get_auth_headers())
def _get_auth_headers(self) -> Dict[str, str]:
        """Helper method to get auth headers."""
        # What's the corresponding method to get the token
        return {
            "apiKey": self.supabase_key,
            "Authorization": f"Bearer {self.supabase_key}",
        }

Describe the solution you'd like

It should be possible to reproduce JS behavior to create client with Auth context of the user that called the function (logged in user's JWT).

Am I missing something ?

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions