mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Problem Several auth callback and email confirmation examples redirect to the `next` query parameter without checking it. A reader who copies one gets an open redirect: anyone can send a sign-in link with `next` set to another site, and the app sends the signed-in user there. The affected examples are the SvelteKit, Astro, Remix, and Express tabs of the PKCE flow partial, which all social sign-in pages include, and the Next.js, Astro, Remix, and Express email confirmation handlers in the password guide. The SvelteKit and Express tabs had a partial check, but `//evil.com` and `/\evil.com` still got through. The SvelteKit confirmation tabs and the Next.js reset tab in the password guide copy `next` into the URL path. That keeps the user on the same site, but turns a full URL into a broken path. The example apps under `examples/` have the same problem. The Next.js email confirmation route in `examples/auth/nextjs-full` has the same open redirect. Two SvelteKit example apps copy `next` into the URL path, which keeps the user on the same site but turns a full URL into a broken path. Resolves [DOCS-1836](https://linear.app/supabase/issue/DOCS-1836/make-the-auth-callback-examples-redirect-only-within-the-app), [DOCS-1840](https://linear.app/supabase/issue/DOCS-1840/make-the-auth-examples-under-examples-redirect-only-within-the-app), and [DOCS-1844](https://linear.app/supabase/issue/DOCS-1844/handle-full-url-and-query-string-next-values-in-the-confirmation). ## Solution Each example now reads `next` as a URL against the request's own origin. It keeps `next` only when the result uses `http` or `https`, has the request's host, and its path doesn't start with `//`, then redirects to that path. Anything else falls back to `/`. The examples accept same-site full URLs as well as paths. The signup email template on the password page sends `next={{ .RedirectTo }}`, which is always a full URL, so a path-only check would send every new user to `/`. #51567 proposed a path-only check for the same examples, and this PR builds on it with full-URL support. The redirect itself stays relative. An absolute URL built from the request origin can point to an internal host when the app runs behind a proxy. `URL.parse()` returns `null` for malformed input, so a bad `next` value or `Host` header falls back to `/` instead of throwing. Each check compares the host of `next` with the request's host. Behind a proxy that terminates HTTPS, Express reports the request as `http`, so comparing full origins would send every full-URL `next` to `/`. The redirect carries only the path, so the scheme doesn't affect where the user lands. Other schemes are rejected, because a URL such as `custom://example.com/\evil.com` keeps the backslash in its path, and browsers read `/\evil.com` as another site. The Express examples also read `next` only when it's a string, because the Express 4 query parser can return an object. The Next.js tab of the PKCE partial already stays on the same site, so it's unchanged. The SvelteKit confirmation tabs and the Next.js reset tab in the password guide get the same check as the other tabs. On success they redirect to the checked value. On failure, the SvelteKit tabs redirect to a fixed error page. The Next.js reset tab now matches the signup tab, so its redirect no longer carries `token_hash` and `type`. The email confirmation routes in three example apps get the same check: `examples/auth/nextjs-full`, `examples/auth/sveltekit-full`, and `examples/user-management/sveltekit-user-management`. The user management example falls back to `/account`, the page its tutorial sends users to. In the SvelteKit routes, a successful confirmation redirects straight to the checked value, and a failed one redirects to a fixed error page. Other query parameters on the confirmation link no longer carry over. The Next.js example pins TypeScript 5.9.3, because TypeScript 5.3 has no type for `URL.parse` and `next build` failed its type check. The SvelteKit tutorial embeds the user management route, so the tutorial shows the new code. ## Verification (`/test-the-docs`) Each handler was extracted by script from the MDX on this branch, on `master`, and on #51567, then mounted in a minimal app for its framework. Each app ran against a local Supabase stack in the Compose sandbox. Confirm handlers got a fresh `generateLink` token hash per case. PKCE callbacks got a real code from a PKCE magic-link sign-in through Mailpit, with the code verifier cookie. Each route ran 12 `next` cases: none, `/welcome`, `/account?tab=1`, a same-site full URL, `//evil.com`, `/\evil.com`, `https://evil.com/x`, `javascript:alert(1)`, `http://`, `/<tab>/evil.com`, `/.//evil.com`, and `/a/..//evil.com`. The same-site full URL uses the origin each server reports for itself. | Example | Framework | This branch | `master` | | --- | --- | --- | --- | | PKCE partial, SvelteKit tab | SvelteKit 2.70 + adapter-node | pass 12/12 | 2 cases off-site | | PKCE partial, Astro tab | Astro 7.4 + @astrojs/node | pass 12/12 with `Astro.*` patched (see below) | 5 cases off-site | | PKCE partial, Remix tab | Remix 2.17 | pass 12/12 | 5 cases off-site | | PKCE partial, Express tab | Express 5.3 | pass 12/12 | 2 cases off-site | | Password signup, Next.js tab | Next.js 16.5 | pass 12/12 | 5 cases off-site | | Password signup and reset, Astro tabs | Astro 7.4 | pass 12/12 each | 5 cases off-site each | | Password signup and reset, Remix tabs | Remix 2.17 | pass 12/12 each | 5 cases off-site each | | Password signup and reset, Express tabs | Express 5.3 | pass 12/12 each | 2 cases off-site each | - `next build` type-checks the Next.js handler. `tsc --strict` reports the same errors for the Remix and Astro handlers as on `master`. - Express falls back to `/` on a malformed `Host` header without crashing. - #51567 also kept every route on the same site, and sent the same-site full URL case to `/`. - The unchanged examples stay on the same site in every case. - After review, each of the 14 changed blocks ran in Node 22 against 32 `next` values. The cases include Express behind an HTTPS proxy, an object `next` from the Express 4 query parser, and custom-scheme URLs with a backslash in the path. - The SvelteKit signup and reset tabs and the Next.js reset tab also ran end to end in Node 22, with `redirect` and `verifyOtp` stubbed. A same-site full URL lands on its path, `/account?tab=1` keeps its query, and the error page URL has no `token_hash` or `type`. On `master`, the same cases redirect to `/https://…`, to `/account%3Ftab=1`, and, in the Next.js reset tab, to a URL that still carries `token_hash`. ### Example apps Each example app was built and run in the Compose sandbox against a local Supabase stack. Every case used a fresh signup token, so each request ran a real `verifyOtp` and set a session cookie. The `sveltekit-full` example has no build setup of its own, so its route ran inside the user management app. Each route ran the 12 cases above, plus the same host on the other scheme and an `ftp://` URL on the same host, plus an invalid token to check the error redirect. | Example | Framework | This branch | `master` | | --- | --- | --- | --- | | `auth/nextjs-full` | Next.js 16.5 | pass 14/14, error path passes | 5 cases off-site | | `user-management/sveltekit-user-management` | SvelteKit 2.70 | pass 14/14, error path passes | on-site, but 9 of 12 cases land on a broken path | | `auth/sveltekit-full` | SvelteKit 2.70 | pass 14/14, error path passes | on-site, but 9 of 12 cases land on a broken path | - `next build` passes. With TypeScript 5.3.3, it fails with `Property 'parse' does not exist`. - `svelte-check` reports the same 7 errors on this branch and on `master`, all in the database types and the account form. None are in the confirm route. - Behind a proxy without forwarded-host handling, `next start` sees `localhost:3000`, so a full-URL `next` falls back to the default page there. ### Found while testing, not changed here These problems are on `master` too, and they're outside the scope of this fix: - PKCE partial, Astro tab: `Astro.request` and `Astro.cookies` don't exist in an API route, so the callback returns a 500 error. Tracked in [DOCS-1841](https://linear.app/supabase/issue/DOCS-1841/make-the-astro-oauth-callback-example-run-in-an-api-route). - Password guide, Remix confirm tabs: `setAll(key, value, options)` doesn't match the `@supabase/ssr` signature, so no session cookie is set after confirming. Tracked in [DOCS-1842](https://linear.app/supabase/issue/DOCS-1842/make-the-remix-email-confirmation-examples-set-the-session-cookie). - Password guide, Express confirm tabs: no `return` after the success redirect, so the error redirect also runs. Express 5 logs `ERR_HTTP_HEADERS_SENT`, and Express 4 exits the process. Tracked in [DOCS-1843](https://linear.app/supabase/issue/DOCS-1843/stop-the-express-email-confirmation-examples-from-redirecting-twice). - PKCE partial, Express tab: the callback ignores the result of `exchangeCodeForSession`, so a missing code or a failed exchange still redirects to `next`. Tracked in [DOCS-1845](https://linear.app/supabase/issue/DOCS-1845/send-failed-code-exchanges-to-the-error-page-in-the-express-oauth). - PKCE partial and password guide, Astro tabs: `setAll` drops the cache headers that `@supabase/ssr` passes with the session cookies. Tracked in [DOCS-1846](https://linear.app/supabase/issue/DOCS-1846/apply-the-cache-headers-from-supabasessr-in-the-astro-auth-callback). - Email templates guide, server-side endpoint example: it redirects to `redirect_to` without checking it. Tracked in [DOCS-1847](https://linear.app/supabase/issue/DOCS-1847/check-redirect-to-before-redirecting-in-the-server-side-email-template). - Next.js examples in the PKCE partial, the password guide, and the WorkOS and Google sign-in guides: they import the Supabase clients from `@/utils/supabase/`, but the client guide now creates them in `lib/supabase/`. Tracked in [DOCS-1848](https://linear.app/supabase/issue/DOCS-1848/import-the-nextjs-supabase-clients-from-libsupabase-in-the-auth). ## Review category (docs PRs only) - [ ] Critical: needs a review as soon as possible - [ ] Urgent: the feature ships soon, or it's blocking something else - [ ] Moderate: good to have soon, not urgent - [x] Low: get to it when you can ## Review instructions 1. Check that each changed example only touches the `next` handling and its redirect. 2. Check the changed tabs on the preview: - [GitHub sign-in page on the preview](https://docs-git-alexisa-docs-1836-supabase.vercel.app/docs/guides/auth/social-sign-in/auth-github): the callback code for the SvelteKit, Astro, Remix, and Express tabs. Every social sign-in page includes this partial. - [Password guide on the preview](https://docs-git-alexisa-docs-1836-supabase.vercel.app/docs/guides/auth/passwords): under PKCE flow, every framework tab for signup confirmation and password reset. - [SvelteKit tutorial on the preview](https://docs-git-alexisa-docs-1836-supabase.vercel.app/docs/guides/getting-started/tutorials/with-sveltekit#confirmation-endpoint): the confirmation endpoint embeds the user management example's route. 3. Check the three confirm routes under `examples/` and the `typescript` pin in `examples/auth/nextjs-full/package.json`. ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] 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). Not used: only code inside existing snippets and example apps changed, no prose. The snippets were verified with `/test-the-docs`.
1561 lines
42 KiB
Plaintext
1561 lines
42 KiB
Plaintext
---
|
|
title: 'Password-based Auth'
|
|
subtitle: 'Allow users to sign in with a password connected to their email or phone number.'
|
|
tocVideo: 'Ufx6fdRMxjU'
|
|
---
|
|
|
|
Users often expect to sign in to your site with a password. Supabase Auth helps you implement password-based auth safely, using secure configuration options and best practices for storing and verifying passwords.
|
|
|
|
Users can associate a password with their identity using their [email address](#with-email) or a [phone number](#with-phone).
|
|
|
|
<Admonition type="warning" title="Reset database password">
|
|
Looking for a database password? See [Reset database
|
|
password](/kb/troubleshooting/how-do-i-reset-my-supabase-database-password-oTs5sB).
|
|
</Admonition>
|
|
|
|
## With email
|
|
|
|
### Enabling email and password-based authentication
|
|
|
|
Email authentication is enabled by default.
|
|
|
|
You can configure whether users need to verify their email to sign in. On hosted Supabase projects, this is true by default. On self-hosted projects or in local development, this is false by default.
|
|
|
|
Change this setting on the [Auth Providers page](/dashboard/project/_/auth/providers) for hosted projects, or in the [configuration file](/docs/guides/local-development/cli/config#auth.email.enable_confirmations) for self-hosted projects.
|
|
|
|
### Signing up with an email and password
|
|
|
|
There are two possible flows for email signup: [implicit flow](/docs/guides/auth/sessions/implicit-flow) and [PKCE flow](/docs/guides/auth/sessions/pkce-flow). If you're using SSR, you're using the PKCE flow. If you're using client-only code, the default flow depends upon the client library. The implicit flow is the default in JavaScript and Dart, and the PKCE flow is the default in Swift.
|
|
|
|
The instructions in this section assume that email confirmations are enabled.
|
|
|
|
<Tabs
|
|
scrollable
|
|
stickyTabList={{
|
|
style: {
|
|
top: 'var(--header-height)',
|
|
maskImage: 'none',
|
|
}
|
|
}}
|
|
size="large"
|
|
type="underlined"
|
|
queryGroup="flow"
|
|
>
|
|
<TabPanel id="implicit" label="Implicit flow">
|
|
|
|
The implicit flow only works for client-only apps. Your site directly receives the access token after the user confirms their email.
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/javascript/auth-signup) with their email address and password.
|
|
|
|
You can optionally specify a URL to redirect to after the user clicks the confirmation link. This URL must be configured as a [Redirect URL](/docs/guides/auth/redirect-urls), which you can do in the [dashboard](/dashboard/project/_/auth/url-configuration) for hosted projects, or in the [configuration file](/docs/guides/local-development/cli/config#auth.additional_redirect_urls) for self-hosted projects.
|
|
|
|
If you don't specify a redirect URL, the user is automatically redirected to your site URL. This defaults to `localhost:3000`, but you can also configure this.
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
async function signUpNewUser() {
|
|
const { data, error } = await supabase.auth.signUp({
|
|
email: 'valid.email@supabase.io',
|
|
password: 'example-password',
|
|
options: {
|
|
emailRedirectTo: 'https://example.com/welcome',
|
|
},
|
|
})
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/dart/auth-signup) with their email address and password:
|
|
|
|
```dart
|
|
Future<void> signUpNewUser() async {
|
|
final AuthResponse res = await supabase.auth.signUp(
|
|
email: 'valid.email@supabase.io',
|
|
password: 'example-password'
|
|
);
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/swift/auth-signup) with their email address and password.
|
|
|
|
You can optionally specify a URL to redirect to after the user clicks the confirmation link. This URL must be configured as a [Redirect URL](/docs/guides/auth/redirect-urls), which you can do in the [dashboard](/dashboard/project/_/auth/url-configuration) for hosted projects, or in the [configuration file](/docs/guides/local-development/cli/config#auth.additional_redirect_urls) for self-hosted projects.
|
|
|
|
If you don't specify a redirect URL, the user is automatically redirected to your site URL. This defaults to `localhost:3000`, but you can also configure this.
|
|
|
|
```swift
|
|
let response = try await supabase.auth.signUp(
|
|
email: "valid.email@supabase.io",
|
|
password: "example-password",
|
|
redirectTo: URL(string: "https://example.com/welcome")
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
To sign up the user, call [signUpWith(Email)](/docs/reference/kotlin/auth-signup) with their email address and password:
|
|
|
|
```kotlin
|
|
suspend fun signUpNewUser() {
|
|
supabase.auth.signUpWith(Email) {
|
|
email = "valid.email@supabase.io"
|
|
password = "example-password"
|
|
}
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/python/auth-signup) with their email address and password.
|
|
|
|
You can optionally specify a URL to redirect to after the user clicks the confirmation link. This URL must be configured as a [Redirect URL](/docs/guides/auth/redirect-urls), which you can do in the [dashboard](/dashboard/project/_/auth/url-configuration) for hosted projects, or in the [configuration file](/docs/guides/local-development/cli/config#auth.additional_redirect_urls) for self-hosted projects.
|
|
|
|
If you don't specify a redirect URL, the user is automatically redirected to your site URL. This defaults to `localhost:3000`, but you can also configure this.
|
|
|
|
```python
|
|
data = await supabase.auth.sign_up({
|
|
'email': 'valid.email@supabase.io',
|
|
'password': 'example-password',
|
|
'options': {
|
|
'email_redirect_to': 'https://example.com/welcome',
|
|
},
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
To sign up the user, call [`SignUp()`](/docs/reference/csharp/auth-signup) with their email address and password. You can optionally specify a URL to redirect to after the user clicks the confirmation link.
|
|
|
|
```c#
|
|
var options = new SignUpOptions { RedirectTo = "https://example.com/welcome" };
|
|
var session = await supabase.Auth.SignUp("valid.email@supabase.io", "example-password", options);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
</TabPanel>
|
|
|
|
<TabPanel id="pkce" label="PKCE flow">
|
|
|
|
The PKCE flow allows for server-side authentication. Unlike the implicit flow, which directly provides your app with the access token after the user clicks the confirmation link, the PKCE flow requires an intermediate token exchange step before you can get the access token.
|
|
|
|
##### Step 1: Update signup confirmation email
|
|
|
|
Update your signup email template to send the token hash. For detailed instructions on how to configure your email templates, including the use of variables like `{{ .SiteURL }}`, `{{ .TokenHash }}`, and `{{ .RedirectTo }}`, refer to our [Email Templates](/docs/guides/auth/auth-email-templates) guide.
|
|
|
|
Your signup email template should contain the following HTML:
|
|
|
|
```html
|
|
<h2>Confirm your email address</h2>
|
|
|
|
<p>Follow the link below to confirm this email address and finish signing up.</p>
|
|
<p>
|
|
<a
|
|
href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email&next={{ .RedirectTo }}"
|
|
>Confirm email address</a
|
|
>
|
|
</p>
|
|
```
|
|
|
|
##### Step 2: Create token exchange endpoint
|
|
|
|
Create an API endpoint at `<YOUR_SITE_URL>/auth/confirm` to handle the token exchange.
|
|
|
|
<$Partial path="create_client_snippet.mdx" />
|
|
|
|
<Tabs scrollable size="small" type="underlined" defaultActiveId="nextjs" queryGroup="framework">
|
|
<TabPanel id="nextjs" label="Next.js">
|
|
|
|
Create a new file at `app/auth/confirm/route.ts` and populate with the following:
|
|
|
|
```ts app/auth/confirm/route.ts
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
import { redirect } from 'next/navigation'
|
|
import { type NextRequest } from 'next/server'
|
|
|
|
import { createClient } from '@/utils/supabase/server'
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const { searchParams, origin, host } = new URL(request.url)
|
|
const token_hash = searchParams.get('token_hash')
|
|
const type = searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(searchParams.get('next') ?? '/', origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
|
|
if (token_hash && type) {
|
|
const supabase = await createClient()
|
|
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
if (!error) {
|
|
// redirect user to specified redirect URL or root of app
|
|
redirect(next)
|
|
}
|
|
}
|
|
|
|
// redirect the user to an error page with some instructions
|
|
redirect('/auth/auth-code-error')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<TabPanel id="sveltekit" label="SvelteKit">
|
|
|
|
Create a new file at `src/routes/auth/confirm/+server.ts` and populate with the following:
|
|
|
|
```ts src/routes/auth/confirm/+server.ts
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
import { redirect } from '@sveltejs/kit'
|
|
|
|
export const GET = async (event) => {
|
|
const {
|
|
url,
|
|
locals: { supabase },
|
|
} = event
|
|
const token_hash = url.searchParams.get('token_hash') as string
|
|
const type = url.searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(url.searchParams.get('next') ?? '/', url.origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === url.host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
|
|
if (token_hash && type) {
|
|
const { error } = await supabase.auth.verifyOtp({ token_hash, type })
|
|
if (!error) {
|
|
redirect(303, next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
redirect(303, '/auth/error')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
|
|
<TabPanel id="astro" label="Astro">
|
|
|
|
Create a new file at `src/pages/auth/confirm.ts` and populate with the following:
|
|
|
|
```ts src/pages/auth/confirm.ts
|
|
import { createServerClient, parseCookieHeader } from '@supabase/ssr'
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
import { type APIRoute } from 'astro'
|
|
|
|
export const GET: APIRoute = async ({ request, cookies, redirect }) => {
|
|
const requestUrl = new URL(request.url)
|
|
const token_hash = requestUrl.searchParams.get('token_hash')
|
|
const type = requestUrl.searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(requestUrl.searchParams.get('next') || '/', requestUrl.origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === requestUrl.host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
|
|
if (token_hash && type) {
|
|
const supabase = createServerClient(
|
|
import.meta.env.PUBLIC_SUPABASE_URL,
|
|
import.meta.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY,
|
|
{
|
|
cookies: {
|
|
getAll() {
|
|
return parseCookieHeader(request.headers.get('Cookie') ?? '')
|
|
},
|
|
setAll(cookiesToSet, _headers) {
|
|
cookiesToSet.forEach(({ name, value, options }) => cookies.set(name, value, options))
|
|
},
|
|
},
|
|
}
|
|
)
|
|
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
|
|
if (!error) {
|
|
return redirect(next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
return redirect('/auth/auth-code-error')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
|
|
<TabPanel id="remix" label="Remix">
|
|
|
|
Create a new file at `app/routes/auth.confirm.tsx` and populate with the following:
|
|
|
|
```ts app/routes/auth.confirm.tsx
|
|
import { redirect, type LoaderFunctionArgs } from '@remix-run/node'
|
|
import { createServerClient, parseCookieHeader, serializeCookieHeader } from '@supabase/ssr'
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
|
|
export async function loader({ request }: LoaderFunctionArgs) {
|
|
const requestUrl = new URL(request.url)
|
|
const token_hash = requestUrl.searchParams.get('token_hash')
|
|
const type = requestUrl.searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(requestUrl.searchParams.get('next') || '/', requestUrl.origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === requestUrl.host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
const headers = new Headers()
|
|
|
|
if (token_hash && type) {
|
|
const supabase = createServerClient(
|
|
process.env.SUPABASE_URL!,
|
|
process.env.SUPABASE_PUBLISHABLE_KEY!,
|
|
{
|
|
cookies: {
|
|
getAll() {
|
|
return parseCookieHeader(request.headers.get('Cookie') ?? '')
|
|
},
|
|
setAll(key, value, options) {
|
|
headers.append('Set-Cookie', serializeCookieHeader(key, value, options))
|
|
},
|
|
},
|
|
}
|
|
)
|
|
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
|
|
if (!error) {
|
|
return redirect(next, { headers })
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with instructions
|
|
return redirect('/auth/auth-code-error', { headers })
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<TabPanel id="express" label="Express">
|
|
|
|
Create a new route in your express app and populate with the following:
|
|
|
|
```js app.js
|
|
// The client you created from the Server-Side Auth instructions
|
|
const { createClient } = require("./lib/supabase")
|
|
...
|
|
app.get("/auth/confirm", async function (req, res) {
|
|
const token_hash = req.query.token_hash
|
|
const type = req.query.type
|
|
// Keep "next" only when it points to this site
|
|
const site = URL.parse(`${req.protocol}://${req.get("host")}`)
|
|
const target = site && URL.parse(typeof req.query.next === "string" ? req.query.next : "/", site)
|
|
const next =
|
|
target &&
|
|
["http:", "https:"].includes(target.protocol) &&
|
|
target.host === site.host &&
|
|
!target.pathname.startsWith("//")
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: "/"
|
|
|
|
if (token_hash && type) {
|
|
const supabase = createClient({ req, res })
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
if (!error) {
|
|
res.redirect(303, next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
res.redirect(303, '/auth/auth-code-error')
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
##### Step 3: Call the sign up function to initiate the flow
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/javascript/auth-signup) with their email address and password:
|
|
|
|
You can optionally specify a URL to redirect to after the user clicks the confirmation link. This URL must be configured as a [Redirect URL](/docs/guides/auth/redirect-urls), which you can do in the [dashboard](/dashboard/project/_/auth/url-configuration) for hosted projects, or in the [configuration file](/docs/guides/local-development/cli/config#auth.additional_redirect_urls) for self-hosted projects.
|
|
|
|
If you don't specify a redirect URL, the user is automatically redirected to your site URL. This defaults to `localhost:3000`, but you can also configure this.
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
async function signUpNewUser() {
|
|
const { data, error } = await supabase.auth.signUp({
|
|
email: 'valid.email@supabase.io',
|
|
password: 'example-password',
|
|
options: {
|
|
emailRedirectTo: 'https://example.com/welcome',
|
|
},
|
|
})
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/dart/auth-signup) with their email address and password:
|
|
|
|
```dart
|
|
Future<void> signUpNewUser() async {
|
|
final AuthResponse res = await supabase.auth.signUp(
|
|
email: 'valid.email@supabase.io',
|
|
password: 'example-password'
|
|
);
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/swift/auth-signup) with their email address and password:
|
|
|
|
```swift
|
|
let response = try await supabase.auth.signUp(
|
|
email: "valid.email@supabase.io",
|
|
password: "example-password",
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
To sign up the user, call [signUpWith(Email)](/docs/reference/kotlin/auth-signup) with their email address and password:
|
|
|
|
```kotlin
|
|
suspend fun signUpNewUser() {
|
|
supabase.auth.signUpWith(Email) {
|
|
email = "valid.email@supabase.io"
|
|
password = "example-password"
|
|
}
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
To sign up the user, call [signUp()](/docs/reference/python/auth-signup) with their email address and password:
|
|
|
|
```python
|
|
data = supabase.auth.sign_up({
|
|
'email': 'valid.email@supabase.io',
|
|
'password': 'example-password',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
To sign up the user, call [`SignUp()`](/docs/reference/csharp/auth-signup) with their email address and password:
|
|
|
|
```c#
|
|
var session = await supabase.Auth.SignUp("valid.email@supabase.io", "example-password");
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
</TabPanel>
|
|
|
|
</Tabs>
|
|
|
|
### Signing in with an email and password
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
When your user signs in, call [`signInWithPassword()`](/docs/reference/javascript/auth-signinwithpassword) with their email address and password:
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
async function signInWithEmail() {
|
|
const { data, error } = await supabase.auth.signInWithPassword({
|
|
email: 'valid.email@supabase.io',
|
|
password: 'example-password',
|
|
})
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
When your user signs in, call [`signInWithPassword()`](/docs/reference/dart/auth-signinwithpassword) with their email address and password:
|
|
|
|
```dart
|
|
Future<void> signInWithEmail() async {
|
|
final AuthResponse res = await supabase.auth.signInWithPassword(
|
|
email: 'valid.email@supabase.io',
|
|
password: 'example-password'
|
|
);
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
When your user signs in, call [signIn(email:password:)](/docs/reference/swift/auth-signinwithpassword) with their email address and password:
|
|
|
|
```swift
|
|
try await supabase.auth.signIn(
|
|
email: "valid.email@supabase.io",
|
|
password: "example-password"
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
When your user signs in, call [signInWith(Email)](/docs/reference/kotlin/auth-signinwithpassword) with their email address and password:
|
|
|
|
```kotlin
|
|
suspend fun signInWithEmail() {
|
|
supabase.auth.signInWith(Email) {
|
|
email = "valid.email@supabase.io"
|
|
password = "example-password"
|
|
}
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
When your user signs in, call [sign_in_with_password()](/docs/reference/python/auth-signinwithpassword) with their email address and password:
|
|
|
|
```python
|
|
data = client.auth.sign_in_with_password({
|
|
'email': 'valid.email@supabase.io',
|
|
'password': 'example-password',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
When your user signs in, call [`SignIn()`](/docs/reference/csharp/auth-signinwithpassword) with their email address and password:
|
|
|
|
```c#
|
|
var session = await supabase.Auth.SignIn("valid.email@supabase.io", "example-password");
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
### Resetting a password
|
|
|
|
<Admonition type="note">
|
|
|
|
To prevent user enumeration, `resetPasswordForEmail()` doesn't reveal whether an account exists for the given email address.
|
|
|
|
When no user is associated with the address, Supabase Auth won't send an email, though the method still returns without an error.
|
|
|
|
</Admonition>
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
queryGroup="flow"
|
|
>
|
|
<TabPanel id="implicit" label="Implicit flow">
|
|
|
|
#### Step 1: Create a reset password page
|
|
|
|
Create a **reset password** page. This page should be publicly accessible.
|
|
|
|
Collect the user's email address and request a password reset email. Specify the redirect URL, which should point to the URL of a **change password** page. This URL needs to be configured in your [redirect URLs](/docs/guides/auth/redirect-urls).
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
await supabase.auth.resetPasswordForEmail('valid.email@supabase.io', {
|
|
redirectTo: 'http://example.com/account/update-password',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
```swift
|
|
try await supabase.auth.resetPasswordForEmail(
|
|
"valid.email@supabase.io",
|
|
redirectTo: URL(string: "http://example.com/account/update-password")
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
```kotlin
|
|
supabase.auth.resetPasswordForEmail(
|
|
email = "valid.email@supabase.io",
|
|
redirectUrl = "http://example.com/account/update-password"
|
|
)
|
|
```
|
|
|
|
If you are on one of the Kotlin targets that have built-in support for redirect URL handling, such as Android, see [OAuth and OTP link verification](/docs/reference/kotlin/initializing).
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
```python
|
|
client.auth.reset_password_email(
|
|
'valid.email@supabase.io',
|
|
{'redirect_to':'http://example.com/account/update-password'}
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
```dart
|
|
await supabase.auth.resetPasswordForEmail(
|
|
'valid.email@supabase.io',
|
|
redirectTo: 'http://example.com/account/update-password',
|
|
);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
```c#
|
|
var options = new ResetPasswordForEmailOptions("valid.email@supabase.io")
|
|
{
|
|
RedirectTo = "http://example.com/account/update-password",
|
|
};
|
|
await supabase.Auth.ResetPasswordForEmail(options);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
#### Step 2: Create a change password page
|
|
|
|
Create a **change password** page at the URL you specified in the previous step. This page should be accessible only to authenticated users.
|
|
|
|
Collect the user's new password and call `updateUser` to update their password.
|
|
|
|
</TabPanel>
|
|
|
|
<TabPanel id="pkce" label="PKCE flow">
|
|
|
|
The PKCE flow allows for server-side authentication. Unlike the implicit flow, which directly provides your app with the access token after the user clicks the confirmation link, the PKCE flow requires an intermediate token exchange step before you can get the access token.
|
|
|
|
##### Step 1: Update reset password email
|
|
|
|
Update your reset password email template to send the token hash. See [Email Templates](/docs/guides/auth/auth-email-templates) for how to configure your email templates.
|
|
|
|
Your reset password email template should contain the following HTML:
|
|
|
|
```html
|
|
<h2>Reset your password</h2>
|
|
|
|
<p>We received a request to reset your password. Follow the link below to choose a new one.</p>
|
|
<p>
|
|
<a
|
|
href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=recovery&next=/account/update-password"
|
|
>Reset password</a
|
|
>
|
|
</p>
|
|
```
|
|
|
|
##### Step 2: Create token exchange endpoint
|
|
|
|
Create an API endpoint at `<YOUR_SITE_URL>/auth/confirm` to handle the token exchange.
|
|
|
|
<$Partial path="create_client_snippet.mdx" />
|
|
|
|
<Tabs scrollable size="small" type="underlined" defaultActiveId="nextjs" queryGroup="framework">
|
|
<TabPanel id="nextjs" label="Next.js">
|
|
|
|
Create a new file at `app/auth/confirm/route.ts` and populate with the following:
|
|
|
|
```ts app/auth/confirm/route.ts
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
import { redirect } from 'next/navigation'
|
|
import { type NextRequest } from 'next/server'
|
|
|
|
// The client you created from the Server-Side Auth instructions
|
|
import { createClient } from '@/utils/supabase/server'
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const { searchParams, origin, host } = new URL(request.url)
|
|
const token_hash = searchParams.get('token_hash')
|
|
const type = searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(searchParams.get('next') ?? '/', origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
|
|
if (token_hash && type) {
|
|
const supabase = await createClient()
|
|
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
if (!error) {
|
|
redirect(next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
redirect('/auth/auth-code-error')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<TabPanel id="sveltekit" label="SvelteKit">
|
|
|
|
Create a new file at `src/routes/auth/confirm/+server.ts` and populate with the following:
|
|
|
|
```ts src/routes/auth/confirm/+server.ts
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
import { redirect } from '@sveltejs/kit'
|
|
|
|
export const GET = async (event) => {
|
|
const {
|
|
url,
|
|
locals: { supabase },
|
|
} = event
|
|
const token_hash = url.searchParams.get('token_hash') as string
|
|
const type = url.searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(url.searchParams.get('next') ?? '/', url.origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === url.host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
|
|
if (token_hash && type) {
|
|
const { error } = await supabase.auth.verifyOtp({ token_hash, type })
|
|
if (!error) {
|
|
redirect(303, next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
redirect(303, '/auth/error')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
|
|
<TabPanel id="astro" label="Astro">
|
|
|
|
Create a new file at `src/pages/auth/confirm.ts` and populate with the following:
|
|
|
|
```ts src/pages/auth/confirm.ts
|
|
import { createServerClient, parseCookieHeader } from '@supabase/ssr'
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
import { type APIRoute } from 'astro'
|
|
|
|
export const GET: APIRoute = async ({ request, cookies, redirect }) => {
|
|
const requestUrl = new URL(request.url)
|
|
const token_hash = requestUrl.searchParams.get('token_hash')
|
|
const type = requestUrl.searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(requestUrl.searchParams.get('next') || '/', requestUrl.origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === requestUrl.host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
|
|
if (token_hash && type) {
|
|
const supabase = createServerClient(
|
|
import.meta.env.PUBLIC_SUPABASE_URL,
|
|
import.meta.env.PUBLIC_SUPABASE_PUBLISHABLE_KEY,
|
|
{
|
|
cookies: {
|
|
getAll() {
|
|
return parseCookieHeader(request.headers.get('Cookie') ?? '')
|
|
},
|
|
setAll(cookiesToSet, _headers) {
|
|
cookiesToSet.forEach(({ name, value, options }) => cookies.set(name, value, options))
|
|
},
|
|
},
|
|
}
|
|
)
|
|
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
|
|
if (!error) {
|
|
return redirect(next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
return redirect('/auth/auth-code-error')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
|
|
<TabPanel id="remix" label="Remix">
|
|
|
|
Create a new file at `app/routes/auth.confirm.tsx` and populate with the following:
|
|
|
|
```ts app/routes/auth.confirm.tsx
|
|
import { redirect, type LoaderFunctionArgs } from '@remix-run/node'
|
|
import { createServerClient, parseCookieHeader, serializeCookieHeader } from '@supabase/ssr'
|
|
import { type EmailOtpType } from '@supabase/supabase-js'
|
|
|
|
export async function loader({ request }: LoaderFunctionArgs) {
|
|
const requestUrl = new URL(request.url)
|
|
const token_hash = requestUrl.searchParams.get('token_hash')
|
|
const type = requestUrl.searchParams.get('type') as EmailOtpType | null
|
|
// Keep "next" only when it points to this site
|
|
const target = URL.parse(requestUrl.searchParams.get('next') || '/', requestUrl.origin)
|
|
const next =
|
|
target &&
|
|
['http:', 'https:'].includes(target.protocol) &&
|
|
target.host === requestUrl.host &&
|
|
!target.pathname.startsWith('//')
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: '/'
|
|
const headers = new Headers()
|
|
|
|
if (token_hash && type) {
|
|
const supabase = createServerClient(
|
|
process.env.SUPABASE_URL!,
|
|
process.env.SUPABASE_PUBLISHABLE_KEY!,
|
|
{
|
|
cookies: {
|
|
getAll() {
|
|
return parseCookieHeader(request.headers.get('Cookie') ?? '')
|
|
},
|
|
setAll(key, value, options) {
|
|
headers.append('Set-Cookie', serializeCookieHeader(key, value, options))
|
|
},
|
|
},
|
|
}
|
|
)
|
|
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
|
|
if (!error) {
|
|
return redirect(next, { headers })
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with instructions
|
|
return redirect('/auth/auth-code-error', { headers })
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<TabPanel id="express" label="Express">
|
|
|
|
Create a new route in your express app and populate with the following:
|
|
|
|
```js app.js
|
|
// The client you created from the Server-Side Auth instructions
|
|
const { createClient } = require("./lib/supabase")
|
|
...
|
|
app.get("/auth/confirm", async function (req, res) {
|
|
const token_hash = req.query.token_hash
|
|
const type = req.query.type
|
|
// Keep "next" only when it points to this site
|
|
const site = URL.parse(`${req.protocol}://${req.get("host")}`)
|
|
const target = site && URL.parse(typeof req.query.next === "string" ? req.query.next : "/", site)
|
|
const next =
|
|
target &&
|
|
["http:", "https:"].includes(target.protocol) &&
|
|
target.host === site.host &&
|
|
!target.pathname.startsWith("//")
|
|
? `${target.pathname}${target.search}${target.hash}`
|
|
: "/"
|
|
|
|
if (token_hash && type) {
|
|
const supabase = createClient({ req, res })
|
|
const { error } = await supabase.auth.verifyOtp({
|
|
type,
|
|
token_hash,
|
|
})
|
|
if (!error) {
|
|
res.redirect(303, next)
|
|
}
|
|
}
|
|
|
|
// return the user to an error page with some instructions
|
|
res.redirect(303, '/auth/auth-code-error')
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
##### Step 3: Call the reset password by email function to initiate the flow
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js
|
|
async function resetPassword() {
|
|
const { data, error } = await supabase.auth.resetPasswordForEmail(email)
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
```swift
|
|
try await supabase.auth.resetPasswordForEmail("valid.email@supabase.io")
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
```kotlin
|
|
supabase.auth.resetPasswordForEmail(
|
|
email = "valid.email@supabase.io",
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
```python
|
|
supabase.auth.reset_password_email('valid.email@supabase.io')
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
```dart
|
|
await supabase.auth.resetPasswordForEmail('valid.email@supabase.io');
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
```c#
|
|
await supabase.Auth.ResetPasswordForEmail("valid.email@supabase.io");
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
Once you have a session, collect the user's new password and call `updateUser` to update their password.
|
|
|
|
</TabPanel>
|
|
|
|
</Tabs>
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
await supabase.auth.updateUser({ password: 'new_password' })
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
```swift
|
|
try await supabase.auth.updateUser(user: UserAttributes(password: newPassword))
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
```kotlin
|
|
supabase.auth.updateUser {
|
|
password = "new_password"
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
```python
|
|
supabase.auth.update_user({'password': 'new_password'})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
```dart
|
|
final UserResponse res = await supabase.auth.updateUser(
|
|
UserAttributes(password: 'new_password'),
|
|
);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
```c#
|
|
await supabase.Auth.Update(new UserAttributes { Password = "new_password" });
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
#### Verifying the current password
|
|
|
|
If your app requires users to confirm their current password before setting a new one, you can pass `current_password` (available in `supabase-js` v2.102.0+ and `supabase-kt` 3.5.0+):
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js
|
|
await supabase.auth.updateUser({
|
|
password: 'new_password',
|
|
current_password: 'old_password',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
```kotlin
|
|
supabase.auth.updateUser {
|
|
password = "new_password"
|
|
currentPassword = "old_password"
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
</Tabs>
|
|
|
|
### Email sending
|
|
|
|
The signup confirmation and password reset flows require an SMTP server to send emails.
|
|
|
|
The Supabase platform comes with a default email-sending service for you to try out. The service has a rate limit of <SharedData data="config">auth.rate_limits.email.inbuilt_smtp_per_hour.value</SharedData> emails per hour, and availability is on a best-effort basis. For production use, you should consider configuring a custom SMTP server.
|
|
|
|
<Admonition type="note">
|
|
|
|
Consider configuring a custom SMTP server for production.
|
|
|
|
</Admonition>
|
|
|
|
See the [Custom SMTP guide](/docs/guides/auth/auth-smtp) for instructions.
|
|
|
|
#### Local development with Mailpit
|
|
|
|
The [Supabase CLI](/docs/guides/local-development/cli/getting-started) captures every email from local Auth in Mailpit, so you can test sign-up and password reset without sending email. For the steps, see [Test email flows locally](/docs/guides/auth/testing-auth-flows#test-email-flows-locally).
|
|
|
|
## With phone
|
|
|
|
You can use a user's mobile phone number as an identifier, instead of an email address, when they sign up with a password.
|
|
|
|
This practice is usually discouraged because phone networks recycle mobile phone numbers. Anyone receiving a recycled phone number gets access to the original user's account. To mitigate this risk, [implement MFA](/docs/guides/auth/auth-mfa).
|
|
|
|
<Admonition type="danger">
|
|
|
|
Protect users who use a phone number as a password-based auth identifier by enabling MFA.
|
|
|
|
</Admonition>
|
|
|
|
### Enabling phone and password-based authentication
|
|
|
|
Enable phone authentication on the [Auth Providers page](/dashboard/project/_/auth/providers) for hosted Supabase projects.
|
|
|
|
For self-hosted projects or local development, use the [configuration file](/docs/guides/local-development/cli/config#auth.sms.enable_signup). See the configuration variables namespaced under `auth.sms`.
|
|
|
|
If you want users to confirm their phone number on signup, you need to set up an SMS provider. Each provider has its own configuration. Supported providers include MessageBird, Twilio, Vonage, and TextLocal (community-supported).
|
|
|
|
<AuthSmsProviderConfig />
|
|
|
|
<$Partial path="cost_warning.mdx" />
|
|
|
|
### Signing up with a phone number and password
|
|
|
|
To sign up the user, call [`signUp()`](/docs/reference/javascript/auth-signup) with their phone number and password:
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
const { data, error } = await supabase.auth.signUp({
|
|
phone: '+13334445555',
|
|
password: 'some-password',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
```swift
|
|
try await supabase.auth.signUp(
|
|
phone: "+13334445555",
|
|
password: "some-password"
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
```kotlin
|
|
supabase.auth.signUpWith(Phone) {
|
|
phone = "+13334445555"
|
|
password = "some-password"
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
```python
|
|
supabase.auth.sign_up({
|
|
'phone': "+13334445555",
|
|
'password': "some-password"
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
```dart
|
|
final AuthResponse res = await supabase.auth.signUp(
|
|
phone: '+13334445555',
|
|
password: 'some-password',
|
|
);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
```c#
|
|
var session = await supabase.Auth.SignUp(SignUpType.Phone, "+13334445555", "some-password");
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<TabPanel id="http" label="HTTP">
|
|
|
|
```bash
|
|
curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/signup' \
|
|
-H "apikey: SUPABASE_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"phone": "+13334445555",
|
|
"password": "some-password"
|
|
}'
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
If you have phone verification turned on, the user receives an SMS with a 6-digit pin that you must verify within 60 seconds:
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOtp`:
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
const {
|
|
data: { session },
|
|
error,
|
|
} = await supabase.auth.verifyOtp({
|
|
phone: '+13334445555',
|
|
token: '123456',
|
|
type: 'sms',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`:
|
|
|
|
```swift
|
|
try await supabase.auth.verifyOTP(
|
|
phone: "+13334445555",
|
|
token: "123456",
|
|
type: .sms
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyPhoneOtp`:
|
|
|
|
```kotlin
|
|
supabase.auth.verifyPhoneOtp(
|
|
type = OtpType.Phone.SMS,
|
|
phone = "+13334445555",
|
|
token = "123456"
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verify_otp`:
|
|
|
|
```python
|
|
supabase.auth.verify_otp({
|
|
'phone': "+13334445555",
|
|
'token': "123456",
|
|
'type': "sms"
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
You should present a form to the user so they can input the 6 digit pin, then send it along with the phone number to `verifyOTP`:
|
|
|
|
```dart
|
|
final AuthResponse res = await supabase.auth.verifyOTP(
|
|
phone: '+13334445555',
|
|
token: '123456',
|
|
type: OtpType.sms,
|
|
);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
```c#
|
|
var session = await supabase.Auth.VerifyOTP("+13334445555", "123456", MobileOtpType.SMS);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<TabPanel id="http" label="HTTP">
|
|
|
|
```bash
|
|
curl -X POST 'https://<PROJECT_REF>.supabase.co/auth/v1/verify' \
|
|
-H "apikey: <SUPABASE_KEY>" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"type": "sms",
|
|
"phone": "+13334445555",
|
|
"token": "123456"
|
|
}'
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
### Signing in a with a phone number and password
|
|
|
|
Call the function to sign in with the user's phone number and password:
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js
|
|
import { createClient } from '@supabase/supabase-js'
|
|
|
|
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
|
|
|
|
// ---cut---
|
|
const { data, error } = await supabase.auth.signInWithPassword({
|
|
phone: '+13334445555',
|
|
password: 'some-password',
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
<$Show if="sdk:swift">
|
|
<TabPanel id="swift" label="Swift">
|
|
|
|
```swift
|
|
try await supabase.auth.signIn(
|
|
phone: "+13334445555",
|
|
password: "some-password"
|
|
)
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:kotlin">
|
|
<TabPanel id="kotlin" label="Kotlin">
|
|
|
|
```kotlin
|
|
supabase.auth.signInWith(Phone) {
|
|
phone = "+13334445555"
|
|
password = "some-password"
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:python">
|
|
<TabPanel id="python" label="Python">
|
|
|
|
```python
|
|
supabase.auth.sign_in_with_password({
|
|
'phone': "+13334445555",
|
|
'password': "some-password"
|
|
})
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:dart">
|
|
<TabPanel id="dart" label="Dart">
|
|
|
|
```dart
|
|
final AuthResponse res = await supabase.auth.signInWithPassword(
|
|
phone: '+13334445555',
|
|
password: 'some-password',
|
|
);
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<$Show if="sdk:csharp">
|
|
<TabPanel id="csharp" label="C#">
|
|
|
|
```c#
|
|
var session = await supabase.Auth.SignIn(SignInType.Phone, "+13334445555", "some-password");
|
|
```
|
|
|
|
</TabPanel>
|
|
</$Show>
|
|
<TabPanel id="http" label="HTTP">
|
|
|
|
```bash
|
|
curl -X POST 'https://cvwawazfelidkloqmbma.supabase.co/auth/v1/token?grant_type=password' \
|
|
-H "apikey: SUPABASE_KEY" \
|
|
-H "Content-Type: application/json" \
|
|
-d '{
|
|
"phone": "+13334445555",
|
|
"password": "some-password"
|
|
}'
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
## Related resources
|
|
|
|
- [Pre-built password authentication web block](/library/docs/nextjs/password-based-auth)
|