Auth

Amazon Cognito (Amplify)

Use Amazon Cognito via Amplify or standalone with your Supabase project


Amazon Cognito User Pools (via AWS Amplify or on its own) can be used as a third-party authentication provider alongside Supabase Auth, or standalone, with your Supabase project.

Getting started

  1. First you need to add an integration to connect your Supabase project with your Amazon Cognito User Pool. You will need the pool's ID and region.
  2. Add a new Third-party Auth integration in your project's Authentication settings or configure it in the CLI.
  3. Assign the role: 'authenticated' custom claim to all JWTs by using a Pre-Token Generation Trigger.
  4. Finally setup the Supabase client in your application.

Setup the Supabase client library


_15
import { fetchAuthSession, Hub } from 'aws-amplify/auth'
_15
_15
const supabase = createClient('https://<supabase-project>.supabase.co', 'SUPABASE_ANON_KEY', {
_15
accessToken: async () => {
_15
const tokens = await fetchAuthSession()
_15
_15
// Alternatively you can use tokens?.idToken instead.
_15
return tokens?.accessToken
_15
},
_15
})
_15
_15
// if you're using Realtime you also need to set up a listener for Cognito auth changes
_15
Hub.listen('auth', () => {
_15
fetchAuthSession().then((tokens) => supabase.realtime.setAuth(tokens?.accessToken))
_15
})

Add a new Third-Party Auth integration to your project

In the dashboard navigate to your project's Authentication settings and find the Third-Party Auth section to add a new integration.

In the CLI add the following config to your supabase/config.toml file:


_10
[auth.third_party.aws_cognito]
_10
enabled = true
_10
user_pool_id = "<id>"
_10
user_pool_region = "<region>"

Use a Pre-Token Generation Trigger to assign the authenticated role

Your Supabase project inspects the role claim present in all JWTs sent to it, to assign the correct Postgres role when using the Data API, Storage or Realtime authorization.

By default, Amazon Cognito JWTs (both ID token and access tokens) do not contain a role claim in them. If you were to send such a JWT to your Supabase project, the anon role would be assigned when executing the Postgres query. Most of your app's logic will be accessible by the authenticated role.

A recommended approach to do this is to configure a Pre-Token Generation Trigger either V1_0 (ID token only) or V2_0 (both access and ID token). To do this you will need to create a new Lambda function (in any language and runtime) and assign it to the Amazon Cognito User Pool's Lambda Triggers configuration. For example, the Lambda function should look similar to this:


_11
export const handler = async (event) => {
_11
event.response = {
_11
claimsOverrideDetails: {
_11
claimsToAddOrOverride: {
_11
role: 'authenticated',
_11
},
_11
},
_11
}
_11
_11
return event
_11
}