Files
supabase/apps/docs/content/guides/auth/jwts.mdx
Miranda Limonczenko b66bedd1c9 docs(guides): rework five explainer pages to the explainer template (#53755)
## Problem

Five concept pages are close to the explainer template from #53751 but
don't follow it. They have no value statement and no Related resources,
and they have style gaps such as missing descriptions, topic-name alt
text, and a diagram with no accessibility title or description.

Part of DOCS-1617. A second batch of five pages is in #53757.

## Solution

The PR is one squashed commit. It covers a style pass, the restructure
to the template, critic-pass fixes, tables and lists, the opener change,
and content moved in from other pages.

### Structure

| Page | Change |
| --- | --- |
| `auth/architecture` | Value statement, a `## Layers` table from the
numbered list, Related resources |
| `storage/cdn/fundamentals` | Value statement, `## Example` renamed to
`## How caching works`, Related resources |
| `storage/schema/design` | Retitled `Storage schema`, value statement,
`## Tables` heading, the tables paragraph as a table, Related resources
|
| `storage/security/ownership` | Retitled `Storage ownership` with the
sidebar label `Ownership`, value statement, the deprecated `owner` note
moved into body text, Related resources |
| `auth/identities` | Retitled `Auth identities`, value statement,
Related resources |

- **Linked headings**: headings that other pages link to keep their
text: `#client-layer`, `#auth-service`, `#postgres`,
`#public-vs-private-buckets`, and `#the-user-identity-object`.
- **Openers and tables**: only the value statement and a cross-reference
come before the first heading, and each concept opener moves into the
first H2, per the template change in #53751. Prose comparisons and
parallel facts become tables and lists. On Storage CDN, the cache steps
are a numbered list, and a library analogy follows them.
- **Moved content**: each explainer now owns its concept, and the how-to
that held it links back. Nothing is newly written; every added fact
comes from an existing page:
- Identities: `## How Auth links identities` and `## Limits`, moved from
the Automatic linking section and SAML note in [Identity
linking](/docs/guides/auth/auth-identity-linking), which now links back.
- Storage ownership: who owns a copied or moved object, from [Copy
objects](/docs/guides/storage/management/copy-move-objects), which links
back.
- Auth architecture: `## Limits`, the Auth server's single region, from
[JWTs](/docs/guides/auth/jwts#verifying-a-jwt-from-supabase), which now
keeps only its advice and links back.
- Storage CDN: the extra statuses that count as hits, from [Cache
metrics](/docs/guides/storage/cdn/metrics), which links back.
- **Facts**: unchanged. The value statements, Related resources, and the
CDN analogy are the only new text. Tables, lists, and moved content
restate facts already in the docs.

### Style
- **Descriptions**: add or rewrite one per page, 150 to 160 characters.
- **Alt text**: rewrite against the images. The Auth architecture
diagram now names each route and service, and the two CDN images
describe the cache miss and cache hit.
- **Diagram**: add `accTitle` and `accDescr` to the Storage schema
diagram.
- **Admonitions**: lead with their impact, and cut one that restated the
body text on Auth architecture.
- **Terms**: `WORD_LIST.md` passes for _we_, _will_, _since_, _auto-_,
_ID_, numbers, and spelled-out RLS. External links name their
destination.
- **Subtitles**: cut two that repeated the title or description.

The critic-pass fixes come from a clean-context critic pass against the
style guide.

Facts are unchanged. Skipped on purpose:

- The CDN page's two PNG sequence diagrams aren't converted to Mermaid,
because that's new content.
- `Public vs private buckets` keeps `vs`, because other pages link to
that heading.

### Structure numbers

These numbers are from before the opener and table changes.

| Page | Chars before → after | Headings | Generic headings |
Description chars |
| --- | --- | --- | --- | --- |
| `auth/architecture` | 3,437 → 4,839 | 3 → 5 | 0 → 0 | 0 → 159 |
| `storage/cdn/fundamentals` | 2,617 → 3,632 | 2 → 3 | 1 → 0 | 53 → 152
|
| `storage/schema/design` | 2,819 → 3,875 | 1 → 3 | 0 → 0 | 30 → 154 |
| `storage/security/ownership` | 1,628 → 2,006 | 1 → 2 | 0 → 0 | 71 →
155 |
| `auth/identities` | 3,315 → 4,087 | 1 → 2 | 0 → 0 | 0 → 159 |

Characters grow mostly from descriptions, longer alt text, table
padding, and Related resources. Search top-k isn't recorded, because
there's no fixed query set yet.

### How the template did

- **Fit without changes**: the value statement with a how-to link,
Related resources, the `How <concept> works` Process slot, and the
diagram accessibility rule. The rule caught a real gap on Storage
schema.
- **Fit after a fix in #53751**: the concept heading, one H2 per part,
linked headings in a slot, principles, and the repeated how-to link. See
the learnings in #53751.
- **Still loose**: `auth/architecture` has no concept paragraph of its
own, because the layers are the concept. `storage/security/ownership`
has an `## Access control` section that fits no slot, which is a
principle plus one SQL example.

### Preview

| Page | Live | Preview |
| --- | --- | --- |
| Auth architecture |
[Live](https://supabase.com/docs/guides/auth/architecture) |
[Preview](https://docs-git-docs-explainer-rework-supabase.vercel.app/docs/guides/auth/architecture)
|
| Storage CDN |
[Live](https://supabase.com/docs/guides/storage/cdn/fundamentals) |
[Preview](https://docs-git-docs-explainer-rework-supabase.vercel.app/docs/guides/storage/cdn/fundamentals)
|
| Storage schema |
[Live](https://supabase.com/docs/guides/storage/schema/design) |
[Preview](https://docs-git-docs-explainer-rework-supabase.vercel.app/docs/guides/storage/schema/design)
|
| Storage ownership |
[Live](https://supabase.com/docs/guides/storage/security/ownership) |
[Preview](https://docs-git-docs-explainer-rework-supabase.vercel.app/docs/guides/storage/security/ownership)
|
| Identities | [Live](https://supabase.com/docs/guides/auth/identities)
|
[Preview](https://docs-git-docs-explainer-rework-supabase.vercel.app/docs/guides/auth/identities)
|

## Review instructions

1. Open each page's live and preview links from the Preview table side
by side.
2. Check that each page opens with a value statement and ends with
Related resources.
3. Open `/docs/guides/auth/architecture#client-layer` and
`/docs/guides/storage/cdn/fundamentals#public-vs-private-buckets` on the
preview, and check that each jumps to its heading.
4. On Auth architecture and Storage CDN, compare the new alt text with
the images in `apps/docs/public/img`.
5. On Storage schema, check that the diagram renders and that the tables
table matches it.

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-11-23 16:18:11 -08:00

271 lines
13 KiB
Plaintext

---
id: 'auth-jwts'
title: 'JSON Web Token (JWT)'
subtitle: 'Information on how best to use JSON Web Tokens with Supabase'
tocVideo: 'Ufx6fdRMxjU'
---
A [JSON Web Token](https://jwt.io/introduction) is a type of data structure, represented as a string, that usually contains identity and authorization information about a user. It encodes information about its lifetime and is signed with a cryptographic key to make it tamper-resistant.
Supabase Auth continuously issues a new JWT for each user session, for as long as the user remains signed in. Check the comprehensive guide on [Sessions](/docs/guides/auth/sessions) to find out how you can tailor this process for your needs.
JWTs provide the foundation for [Row Level Security](/docs/guides/database/postgres/row-level-security). Each Supabase product is able to securely decode and verify the validity of a JWT it receives before using Postgres policies and roles to authorize access to the project's data.
Supabase provides a comprehensive system of managing [JWT Signing Keys](/docs/guides/auth/signing-keys) used to create and verify JSON Web Tokens.
## Introduction
JWTs are strings that have the following structure:
```
<header>.<payload>.<signature>
```
Each part is a string of [Base64-URL](https://en.wikipedia.org/wiki/Base64#Variants_summary_table) encoded JSON, or bytes for the signature.
**Header**
```json
{
"typ": "JWT",
"alg": "<HS256 | ES256 | RS256>",
"kid": "<unique key identifier>"
}
```
Gives some basic identifying information about the string, indicating its type `typ`, the cryptographic algorithm `alg` that can be used to verify the data, and optionally the unique key identifier that should be used when verifying it.
**Payload**
```json
{
"iss": "https://project_id.supabase.co/auth/v1",
"exp": 12345678,
"sub": "<user ID>",
"role": "authenticated",
"email": "someone@example.com",
"phone": "+15552368"
// ...
}
```
Provides identifying information (called "claims") about the user (or other entity) that is represented by the token. Usually a JWT conveys information about what the user can access (then called Access Token) or who the user is (then called ID Token). You can use a [Custom Access Token Hook](/docs/guides/auth/auth-hooks/custom-access-token-hook) to add, remove or change claims present in the token. A few claims are important:
| Claim | Description |
| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `iss` | Identifies the server which issued the token. If you append `/.well-known/jwks.json` to this URL you'll get access to the public keys with which you can verify the token. |
| `exp` | Sets a time limit after which the token should not be trusted and is considered expired, even if it is properly signed. |
| `sub` | Means _subject_, is the unique ID of the user represented by the token. |
| <span className="whitespace-nowrap!">`role`</span> | The [Postgres role](/docs/guides/database/postgres/roles) to use when applying Row Level Security policies. |
| ... | All other claims are useful for quick access to profile information without having to query the database or send a request to the Auth server. |
**Signature**
A [digital signature](https://en.wikipedia.org/wiki/Digital_signature) using a [shared secret](https://en.wikipedia.org/wiki/HMAC) or [public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). The purpose of the signature is to verify the authenticity of the `<header>.<payload>` string without relying on database access, liveness or performance of the Auth server. To verify the signature avoid implementing the algorithms yourself and instead rely on `supabase.auth.getClaims()`, or other high-quality JWT verification libraries for your language.
## Supabase and JWTs
Supabase creates JWTs in these cases for you:
1. **When using Supabase Auth, an access token (JWT) is created for each user while they remain signed in**. These are short lived, so they are continuously issued as your user interacts with Supabase APIs.
2. **On-the-fly when using publishable or secret API keys**. Each API key is transformed into a short-lived JWT that is then used to authorize access to your data. Accessing these short-lived tokens is generally not possible.
In addition to creating JWTs, Supabase can also accept JWTs from other authentication servers via the [Third-Party Auth](/docs/guides/auth/third-party/overview) feature or ones that have been minted externally via an imported [JWT Signing Key](/docs/guides/auth/signing-keys).
## Using custom or third-party JWTs
<Admonition type="note">
The `supabase.auth.getClaims()` method is meant to be used only with JWTs issued by Supabase Auth. If you mint your own JWTs using a key you've imported, the verification may fail. We strongly recommend using a JWT verification library for your language to verify this type of JWT based on the claims you're adding in them.
</Admonition>
Your Supabase project accepts a JWT in the `Authorization: Bearer <jwt>` header. If you're using the Supabase client library, it does this for you.
If you are already using Supabase Auth, when a user is signed in, their access token JWT is automatically managed and sent for you with every API call.
If you wish to send a JWT from a Third-Party Auth provider, or one you made yourself by using a JWT signing key you imported, you can pass it to the client library using the `accessToken` option.
<Tabs type="underlined" queryGroup="language">
<TabPanel id="ts" label="TypeScript">
```typescript
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
'https://<supabase-project>.supabase.co',
'SUPABASE_PUBLISHABLE_KEY',
{
accessToken: async () => {
return '<your JWT here>'
},
}
)
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Flutter">
```dart
await Supabase.initialize(
url: supabaseUrl,
publishableKey: supabaseKey,
debug: false,
accessToken: () async {
return "<your JWT here>";
},
);
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift (iOS)">
```swift
import Supabase
let supabase = SupabaseClient(
supabaseURL: URL(string: "https://<supabase-project>.supabase.co")!,
supabaseKey: "SUPABASE_PUBLISHABLE_KEY",
options: SupabaseClientOptions(
auth: SupabaseClientOptions.AuthOptions(
accessToken: {
return "<your JWT here>"
}
)
)
)
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
```kotlin
val supabase = createSupabaseClient(
"https://<supabase-project>.supabase.co",
"SUPABASE_PUBLISHABLE_KEY"
) {
accessToken = {
"<your JWT here>"
}
}
```
</TabPanel>
</$Show>
<TabPanel id="bash" label="cURL">
```bash
curl 'https://<supabase-project>.supabase.co/rest/v1/my_table?select=id' \
-H "apikey: $SUPABASE_PUBLISHABLE_KEY" \
-H "Authorization: Bearer <your JWT here>"
```
</TabPanel>
</Tabs>
In the past there was a recommendation to set custom headers on the Supabase client with the `Authorization` header including your custom JWT. This is no longer recommended as it's less flexible and causes confusion when combined with a user session from Supabase Auth.
## Verifying a JWT from Supabase
If you're not able to use the Supabase client libraries, the following can be used to help you securely verify JWTs issued by Supabase.
Supabase Auth exposes a [JSON Web Key](https://datatracker.ietf.org/doc/html/rfc7517) Set URL for each Supabase project:
```http
GET https://project-id.supabase.co/auth/v1/.well-known/jwks.json
```
Which responds with JWKS object containing one or more asymmetric [JWT signing keys](/docs/guides/auth/signing-keys) (only their public keys). Be aware that this endpoint does not return any keys if you are not using asymmetric JWT signing keys.
```json
{
"keys": [
{
"kid": "<match with kid from JWT header>",
"alg": "<match with alg from JWT header>",
"kty": "<RSA|EC|OKP>",
"key_ops": ["verify"]
// public key fields
}
]
}
```
This endpoint is served directly from the Auth server, but is also additionally cached by the Supabase Edge for 10 minutes, significantly speeding up access to this data regardless of where you're performing the verification. It's important to be aware of the cache expiry time to prevent unintentionally rejecting valid user access tokens. We recommend waiting at least 20 minutes when creating a standby signing key, or revoking a previously used key.
Make sure that you do not cache this data for longer in your application, as it might make revocation difficult. If you do, make sure to provide a way to purge this cache when rotating signing keys to avoid unintentionally rejecting valid user access tokens.
If your backend can't reach this endpoint, see [Public key discovery and caching](/docs/guides/auth/signing-keys#public-key-discovery-and-caching) to copy the public keys into your app.
Below is an example of how to use the [jose TypeScript JWT verification library](https://github.com/panva/jose) with Supabase JWTs:
```typescript
import { createRemoteJWKSet, jwtVerify } from 'jose'
const PROJECT_JWKS = createRemoteJWKSet(
new URL('https://project-id.supabase.co/auth/v1/.well-known/jwks.json')
)
/**
* Verifies the provided JWT against the project's JSON Web Key Set.
*/
async function verifyProjectJWT(jwt: string) {
return jwtVerify(jwt, PROJECT_JWKS)
}
```
### Verifying with a shared secret signing key
If your project is using a shared secret (HS256) signing key, we recommend always verifying a user access token directly with the Auth server by sending a request like so:
```http
GET https://project-id.supabase.co/auth/v1/user
apikey: publishable key
Authorization: Bearer <JWT>
```
If the server responds with HTTP 200 OK, the JWT is valid, otherwise it is not.
This check can be slow, depending on where you perform it. Avoid doing checks like this from servers or functions running on the edge, and prefer routing to a server within the same geographical region as your project. For why, see the limits in [Auth architecture](/docs/guides/auth/architecture#limits).
If you are using a shared secret (HS256) signing key, you may wish to verify using the shared secret. **We strongly recommend against this approach.**
<Admonition type="caution">
There is almost no benefit from using a JWT signed with a shared secret. Although it's computationally more efficient and verification is simpler to code by hand, using this approach can expose your project's data to significant security vulnerabilities or weaknesses.
Consider the following:
- Using a shared secret can make it more difficult to keep aligned with security compliance frameworks such as SOC2, PCI-DSS, ISO27000, HIPAA, etc.
- A shared secret that is in the hands of a malicious actor can be used to impersonate your users, give them access to privileged actions or data.
- It is difficult to detect or identify when or how a shared secret has been given to a malicious actor.
- Consider who might have even accidental access to the shared secret: systems, staff, devices (and their disk encryption and vulnerability patch status).
- A malicious actor can use a shared secret **far into the future**, so lacking current evidence of compromise does not mean your data is secure.
- It can be very easy to accidentally leak the shared secret in publicly available source code such as in your website or frontend, mobile app package or other executable. This is especially true if you accidentally add the secret in environment variables prefixed with `NEXT_PUBLIC_`, `VITE_`, `PUBLIC_` or other conventions by web frameworks.
- Rotating shared secrets might require careful coordination to avoid downtime of your app.
</Admonition>
Check the JWT verification libraries for your language on how to securely verify JWTs signed with a shared secret (HS256) signing key. We strongly recommend relying on the Auth server as described above, or switching to a different signing key based on public key cryptography (RSA, Elliptic Curves) instead.
## Resources
- JWT debugger: https://jwt.io/
- [JWT Signing Keys](/docs/guides/auth/signing-keys)
- [JWT Claims Reference](/docs/guides/auth/jwt-fields) - Complete reference for all JWT claims used by Supabase Auth
- [API keys](/docs/guides/getting-started/api-keys)