
# 

Realtime Authorization

* * *

You can control client access to Realtime [Broadcast](../broadcast/index.md) and [Presence](../presence/index.md) by adding Row Level Security policies to the `realtime.messages` table. Each RLS policy can map to a specific action a client can take:

*   Control which clients can broadcast to a Channel
*   Control which clients can receive broadcasts from a Channel
*   Control which clients can publish their presence to a Channel
*   Control which clients can receive messages about the presence of other clients

Realtime Authorization is in Public Beta. To use Authorization for your Realtime Channels, use `supabase-js` version `v2.44.0` or later.

To enforce private channels you need to disable the 'Allow public access' setting in [Realtime Settings](/dashboard/project/_/realtime/settings)

## How it works[#](#how-it-works)

Realtime uses the `messages` table in your database's `realtime` schema to generate access policies for your clients when they connect to a Channel topic.

By creating RLS policies on the `realtime.messages` table you can control the access users have to a Channel topic, and features within a Channel topic.

The validation is done when the user connects. When their WebSocket connection is established and a Channel topic is joined, their permissions are calculated based on:

*   The RLS policies on the `realtime.messages` table
*   The user information sent as part of their [Auth JWT](../../auth/jwts/index.md)
*   The request headers
*   The Channel topic the user is trying to connect to

When Realtime generates a policy for a client it performs a query on the `realtime.messages` table and then rolls it back. Realtime does not store any messages in your `realtime.messages` table.

Using Realtime Authorization involves two steps:

*   In your database, create RLS policies on the `realtime.messages`
*   In your client, instantiate the Realtime Channel with the `config` option `private: true`

Increased RLS complexity can impact database performance and connection time, leading to higher connection latency and decreased join rates.

## Accessing request information[#](#accessing-request-information)

### `realtime.topic`[#](#realtimetopic)

You can use the `realtime.topic` helper function when writing RLS policies. It returns the Channel topic the user is attempting to connect to.

```
1create policy "authenticated can read all messages on topic"2on "realtime"."messages"3for select4to authenticated5using (6  (select realtime.topic()) = 'room-1'7);
```

### JWT claims[#](#jwt-claims)

The user claims can be accessed using the `current_setting` function. The claims are available as a JSON object in the `request.jwt.claims` setting.

```
1create policy "authenticated with supabase.io email can read all"2on "realtime"."messages"3for select4to authenticated5using (6  -- Only users with the email claim ending with @supabase.io7  (((current_setting('request.jwt.claims'))::json ->> 'email') ~~ '%@supabase.io')8);
```

## Examples[#](#examples)

The following examples use this schema:

```
1create table public.rooms (2    id bigint generated by default as identity primary key,3    topic text not null unique4);56alter table public.rooms enable row level security;78create table public.profiles (9  id uuid not null references auth.users on delete cascade,10  email text NOT NULL,1112  primary key (id)13);1415alter table public.profiles enable row level security;1617create table public.rooms_users (18  user_id uuid references auth.users (id),19  room_topic text references public.rooms (topic),20  created_at timestamptz default current_timestamp21);2223alter table public.rooms_users enable row level security;
```

### Broadcast[#](#broadcast)

The `extension` field on the `realtime.messages` table records the message type. For Broadcast messages, the value of `realtime.messages.extension` is `broadcast`. You can check for this in your RLS policies.

#### Allow a user to join (and read) a Broadcast topic[#](#allow-a-user-to-join-and-read-a-broadcast-topic)

To join a Broadcast Channel, a user must have at least one read or write permission on the Channel topic.

Here, we allow reads (`select`s) for users who are linked to the requested topic within the relationship table `public.room_users`:

```
1create policy "authenticated can receive broadcast"2on "realtime"."messages"3for select4to authenticated5using (6exists (7    select8      user_id9    from10      rooms_users11    where12      user_id = (select auth.uid())13      and room_topic = (select realtime.topic())14      and realtime.messages.extension in ('broadcast')15  )16);
```

Then, to join a topic with RLS enabled, instantiate the Channel with the `private` option set to `true`.

```
1import { createClient } from '@supabase/supabase-js'2const supabase = createClient('your_project_url', 'your_supabase_api_key')34// ---cut---5const channel = supabase.channel('room-1', {6  config: { private: true },7})89channel10  .on('broadcast', { event: 'test' }, (payload) => console.log(payload))11  .subscribe((status, err) => {12    if (status === 'SUBSCRIBED') {13      console.log('Connected!')14    } else {15      console.error(err)16    }17  })
```

#### Allow a user to send a Broadcast message[#](#allow-a-user-to-send-a-broadcast-message)

To authorize sending Broadcast messages, create a policy for `insert` where the value of `realtime.messages.extension` is `broadcast`.

Here, we allow writes (sends) for users who are linked to the requested topic within the relationship table `public.room_users`:

```
1create policy "authenticated can send broadcast on topic"2on "realtime"."messages"3for insert4to authenticated5with check (6  exists (7    select8      user_id9    from10      rooms_users11    where12      user_id = (select auth.uid())13      and room_topic = (select realtime.topic())14      and realtime.messages.extension in ('broadcast')15  )16);
```

### Presence[#](#presence)

The `extension` field on the `realtime.messages` table records the message type. For Presence messages, the value of `realtime.messages.extension` is `presence`. You can check for this in your RLS policies.

#### Allow users to listen to Presence messages on a Channel[#](#allow-users-to-listen-to-presence-messages-on-a-channel)

Create a policy for `select` on `realtime.messages` where `realtime.messages.extension` is `presence`.

```
1create policy "authenticated can listen to presence in topic"2on "realtime"."messages"3for select4to authenticated5using (6  exists (7    select8      user_id9    from10      rooms_users11    where12      user_id = (select auth.uid())13      and room_topic = (select realtime.topic())14      and realtime.messages.extension in ('presence')15  )16);
```

#### Allow users to send Presence messages on a channel[#](#allow-users-to-send-presence-messages-on-a-channel)

To update the Presence status for a user create a policy for `insert` on `realtime.messages` where the value of `realtime.messages.extension` is `presence`.

```
1create policy "authenticated can track presence on topic"2on "realtime"."messages"3for insert4to authenticated5with check (6  exists (7    select8      user_id9    from10      rooms_users11    where12      user_id = (select auth.uid())13      and room_topic = (select realtime.topic())14      and realtime.messages.extension in ('presence')15  )16);
```

### Presence and Broadcast[#](#presence-and-broadcast)

Authorize both Presence and Broadcast by including both extensions in the `where` filter.

#### Broadcast and Presence read[#](#broadcast-and-presence-read)

Authorize Presence and Broadcast read in one RLS policy.

```
1create policy "authenticated can listen to broadcast and presence on topic"2on "realtime"."messages"3for select4to authenticated5using (6  exists (7    select8      user_id9    from10      rooms_users11    where12      user_id = (select auth.uid())13      and room_topic = (select realtime.topic())14      and realtime.messages.extension in ('broadcast', 'presence')15  )16);
```

#### Broadcast and Presence write[#](#broadcast-and-presence-write)

Authorize Presence and Broadcast write in one RLS policy.

```
1create policy "authenticated can send broadcast and presence on topic"2on "realtime"."messages"3for insert4to authenticated5with check (6  exists (7    select8      user_id9    from10      rooms_users11    where12      user_id = (select auth.uid())13      and room_topic = (select realtime.topic())14      and realtime.messages.extension in ('broadcast', 'presence')15  )16);
```

## Interaction with Postgres Changes[#](#interaction-with-postgres-changes)

Realtime Postgres Changes are separate from Channel authorization. The `private` Channel option does not apply to Postgres Changes.

When using Postgres Changes with RLS, database records are sent only to clients who are allowed to read them based on your RLS policies.

## Updating RLS policies[#](#updating-rls-policies)

Client access policies are cached for the duration of the connection. Your database is not queried for every Channel message.

Realtime updates the access policy cache for a client based on your RLS policies when:

*   A client connects to Realtime and subscribes to a Channel
*   A new JWT is sent to Realtime from a client via the [`access_token` message](../protocol/index.md#access-token)

If a new JWT is never received on the Channel, the client will be disconnected when the JWT expires.

Make sure to keep the JWT expiration window short.
