Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Realtime unable to connect with custom token #1113

Open
antonio-bluco opened this issue Aug 2, 2024 · 10 comments
Open

Realtime unable to connect with custom token #1113

antonio-bluco opened this issue Aug 2, 2024 · 10 comments
Labels
bug Something isn't working

Comments

@antonio-bluco
Copy link

Bug report

I am unable to connect to realtime using custom token. I can connect to the table (so RLS works fine), but not to realtime.

Describe the bug

I am unable to have realtime work as expect, even after following all the docs I could find, specifically this and this.

On the server, I authenticate the user, then I create a JWT token:

 const payload = {
    myUserId: userId,
    // Expiry set to 30 min from now
    exp: Math.floor(Date.now() / 1000) + 30 * 60,
  };
const supabaseToken = jwt.sign(payload, process.env.SUPABASE_JWT_SECRET!);

I then pass this token to the client component, and use it as such:

  const supabase = createClient(
    process.env.SUPABASE_URL,
    process.env.SUPABASE_ANON_KEY,
    
     {
       global: {
         headers: {
           Authorization: `Bearer ${supabaseToken}`,
         },
       },
     },
  );
  supabase.realtime.setAuth(supabaseToken);

Then I go to my table, I enable Realtime for that particular table
Screenshot 2024-08-02 at 16 24 51
, and I enable RLS with the condition
USING (auth.checkMyUser() = "userId")
where the checkMyUser function is defined as

CREATE OR REPLACE FUNCTION auth.checkMyUser() returns text as $$
  select nullif(current_setting('request.jwt.claims', true)::json->>'myUserId', '')::text;
$$ language sql stable;

I have checked that the RLS seems to work correctly, because if I do in the client component:

  useEffect(() => {
    const test = async () => {
      const { data } = await supabase
        .from('myTable')
        .select('*');
      console.log('Result: ', JSON.stringify(data, null, 2));
    };
    test();
  }, []);

I see the correct values, which means that the token has been correctly created and parsed by the RLS policy.
However, I can't seem to get any events from the realtime connection created as such:

  useEffect(() => {
    // Listen to all new messages for this organization.
    const channel = supabase
      .channel('myChannel')
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'myTable',
        },
        (payload) => {
          console.log(payload);
        },
      )
      .subscribe();

    // Clean up the connection on exit.
    return () => {
      supabase.removeChannel(channel);
    };
  }, [supabase]);

What is more is, if I change the RLS to allow access to anyone (USING true) , then the realtime connection works and it shows the right results. So it seems to be something wrong in the way the access token is passed to the realtime library, but I have no idea what - all the docs seem to suggest using supabase.realtime.setAuth(token) or perhaps supabase.realtime.accessToken=token;, but neither of these worked.

Can someone help me here? How are we meant to pass custom tokens for authentication?
While we are at it, is there any way to debug this, instead of just trying to guess what the problem is?

@antonio-bluco antonio-bluco added the bug Something isn't working label Aug 2, 2024
@barrownicholas
Copy link
Contributor

This could be because of #1114

@barrownicholas
Copy link
Contributor

@antonio-bluco can you see my comment here #1114 (comment) and try what I suggest (i.e., use npx -y supabase@1.178.6 start to start supabase)? If this fixes your problem, then the real issue is what I describe in my comment and in bug #1114

@antonio-bluco
Copy link
Author

Hi @barrownicholas , thanks a lot for your message!

Unfortunately this seems to be unrelated - I started supabase locally with that version but nothing changed.

@filipecabaco
Copy link
Contributor

are you using realtime locally or in a hosted project? If locally could you provide the logs from realtime and if hosted could you open a support ticket so we can check your project reference directly?

@fullstackwebdev
Copy link

Hi i am suddenly having the same problem after it working for a while and can't figure it out. On hosted

@filipecabaco
Copy link
Contributor

@fullstackwebdev could you provide more details?

@fullstackwebdev
Copy link

  • because supabase auth doesn't support multiple oauth, I need to use next-auth
  • next-auth allows me to set supabaseToken in my request, this works for client and server
  • this also appears to work fine with real time, however

my problem: I get no records for INSERTS or UPDATES when RLS is enabled
I do have hoever get DELETE events.

If I disable RLS, I get all records, but my table is wide open to the world.

I believe the issue is that on the postgres server receving the auth token it is not correctly setting the authenticated role in the SQL connection. In postgraphile I can showyou where this is done, however, I cannot find it in your codebase.

Or it could be complete unrelated issue causing my problems.

Can you please assist me resolving this? Steps to investigate? I believe my theory is correct.

@filipecabaco
Copy link
Contributor

Got it, can you open a ticket so we can follow up with your project reference? That will help us debug a bit better what could be happening.

We do things differently since we do that impersonation using walrus which is a different way of fetching WAL changes with RLS applied.

@fullstackwebdev
Copy link

Got it, can you open a ticket so we can follow up with your project reference? That will help us debug a bit better what could be happening.

We do things differently since we do that impersonation using walrus which is a different way of fetching WAL changes with RLS applied.

supabase/supabase#29542 Would this work?

@filipecabaco
Copy link
Contributor

@fullstackwebdev no as I will need your authorization to work in your project ref.

Use this link : https://supabase.com/dashboard/support/new

but do keep that ticket open as we can use that to discuss and share solutions specific problem after the fact 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants