supabase / supabase-flutter

Flutter integration for Supabase. This package makes it simple for developers to build secure and scalable products.
https://supabase.com/
MIT License
716 stars 168 forks source link

Realtime connection failing when custom JWT is used #962

Open asaki-daisuke opened 3 months ago

asaki-daisuke commented 3 months ago

Describe the bug This issue is related to this. When RLS is disabled on the table, the real-time connection works successfully. However, I would like to enable RLS and verify the custom JWT passed from the Flutter app. It is working fine with SendChat, ReadRoomChats methods. But it's not working with realtime connection.

Looks like it is similar to this issue. We have the following method in TypeScript client to achieve this. client.realtime.setAuth(accessToken);

Current Code

String access_token = await AuthenticationRepository.GetSupabaseToken();
Supabase.initialize(
  url: dotenv.env['SUPABASE_URL'] ?? '',
  anonKey: dotenv.env['SUPABASE_ANON_KEY'] ?? '',
  realtimeClientOptions: const RealtimeClientOptions(
    eventsPerSecond: 2,
  ),
  headers: {
    'Authorization': 'Bearer $access_token',
  }
);

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  ChatBloc(
      {required this.supabaseClient})
      : super(const ChatState()) {
    _listenToNewMessages();
  }

  final SupabaseClient supabaseClient;
  late final RealtimeChannel realtimeChannel;

  void _listenToNewMessages() {
    final realtimeChannel = supabaseClient.channel('public:messages');
    realtimeChannel
      .onPostgresChanges(
          event: PostgresChangeEvent.all,
          schema: 'public',
          table: 'messages',
          callback: (payload) {
            print('New message payload received: $payload');
          })
      .subscribe((status, error) {
        print('Subscribed to messages channel: $status error: $error');
     });

To Reproduce Use the above code and insert a new record into the Supabase table.

Version (please complete the following information): On macOS ├── supabase_flutter 2.5.6 │ ├── supabase 2.2.2 │ │ ├── functions_client 2.2.0 │ │ ├── gotrue 2.8.1 │ │ ├── postgrest 2.1.2 │ │ ├── realtime_client 2.1.0 │ │ ├── storage_client 2.0.2

Additional context

adrean-hipe commented 3 months ago

I experienced the same issue with flutter realtime, realtime works after disabling the RLS on the table. However the solution is not really good since it was used for the authenticated users checking. I wonder if it was due to the access token from JWT not properly initialized to the realtime client instance?

I tried

final client = Supabase.instance.client;
client.realtime.setAuth(access_token);

In flutter to set the access JWT token for the client instance during initialization of Supabase, and it still did not work.