User Authentication (Authentication)
Scenarios
Any commercial application or service that serves end users needs to answer a fundamental question: who is using the application? Applications must identify users, associate data with the correct users, control which content is visible, and track the source of operations. User authentication (Auth) addresses these needs by handling sign-up, sign-in, session persistence, and sign-out. It assigns each user a unique identity and verifies that identity in subsequent requests. Just as a visitor must be identified before being granted access to a building, a user must be identified before being allowed to perform further operations in an application.
Traditionally, customers must develop and maintain their own authentication systems. This involves creating user tables, implementing password encryption and verification, issuing tokens and refreshing sessions, providing password recovery, and integrating third-party identity providers. They must also meet security and compliance requirements, including protection against credential stuffing, replay attacks, and injection attacks, which increases development and maintenance costs.
Huawei Cloud RDS Supabase provides a ready-to-use authentication module that helps developers implement user sign-up, sign-in, and access control quickly and securely, without having to build a complex security foundation from scratch. This can significantly shorten development cycles. Security mechanisms such as password hashing, session security, and brute-force protection are managed by the platform in accordance with modern security standards, reducing the risk of data breaches caused by vulnerabilities in self-built account systems.
The module supports two authentication methods: email and password, and GitHub single sign-on (SSO), covering common sign-in scenarios. It automatically handles the generation, delivery, and refresh of access tokens and refresh tokens to maintain secure login sessions. It is also deeply integrated with row-level security (RLS). After sign-in, a user is assigned an authenticated role. Data reads and writes can be restricted at the database level based on the current user's UID. Unauthenticated users have only the lower-privilege anon role. (Actual row-level data isolation requires appropriate RLS policies. For details, see Database Data APIs.) This module can also be used independently and integrated into your application as needed. This section describes authentication methods, Auth configuration, and SDK operations.
Authentication Methods
Huawei Cloud RDS Supabase supports the following two authentication methods. See Table 1.
| Authentication Method | Use Cases |
|---|---|
| Email authentication (SMTP) | Users register and sign in with an email address and password. The system sends confirmation emails through SMTP to verify email addresses. This method is suitable for applications that manage their own user accounts and serve general users. |
| GitHub OAuth | Users sign in through a third-party GitHub account using SSO, without registering separately in the application. This method is suitable for applications serving developers and technical teams, or those that want to enable quick sign-in through existing GitHub accounts. |
Huawei Cloud RDS Supabase does not support phone number/SMS, WeChat, Alipay, or Google sign-in. GitHub is the only supported third-party OAuth provider.
Authentication Statuses and RLS Roles
The authentication module works with RLS. A user's authentication status determines the database role used to access data, which in turn determines the data the user can see.
| Authentication Status | RLS Role | Description |
|---|---|---|
| Not signed in + Publishable Key | anon | Anonymous user, subject only to anon policies. |
| Signed in + Publishable Key | authenticated | Authenticated user, subject to authenticated policies. |
| Secret Key / Service Role Key | Bypass RLS | Server-side high privilege, bypassing RLS policies. |
Actual row-level data isolation requires appropriate RLS policies. For details, see Database Data APIs.
Auth Configuration
Auth configuration is the centralized console entry for managing authentication capabilities. You can enable or disable authentication methods and configure their parameters, including email authentication, GitHub third-party sign-in, user sign-up, anonymous access, and email templates.
To access Auth configuration, click the Supabase application name to open its details page, where the Auth configuration entry is available. For detailed instructions, see Configuring and Managing User Authentication (Auth).
| Configuration Category | Description |
|---|---|
| Email IDP (SMTP) | SMTP host, port, username, password (authorization code), administrator email address, sender name, automatic email confirmation, and email sending rate limits. For details, see Configuring an Identity Provider (Email). |
| GitHub IDP | Client ID, client secret, and callback URL for the GitHub OAuth app. For details, see Configuring an Identity Provider (GitHub). |
| Access control | Site URL, list of allowed redirect URLs, whether new users can register, and whether anonymous users are allowed. For details, see Access Control. |
| Email templates | Templates for email confirmation, invitations, password resets, email address changes, magic links, reauthentication, and other scenarios. Templates can be hosted in a Storage bucket. For details, see Configuring Email Templates. |
The magic link email template supports passwordless email sign-in (using a one-time login link sent through signInWithOtp). Huawei Cloud RDS Supabase currently focuses on email-and-password authentication. The magic link template is provided as a built-in option for future use as needed and is not covered in this section.
Email Authentication (SMTP)
Simple Mail Transfer Protocol (SMTP) is the standard protocol for sending email. Email authentication relies on an SMTP server to send confirmation and notification emails. It provides an end-to-end authentication flow: sign-up → sign-in → authentication status → user updates (email address and password) → sign-out.
For email authentication, a complete, runnable example guide is provided to simulate a real-world business scenario and demonstrate the end-to-end workflow, from SMTP integration and enabling email authentication to sign-up, sign-in, password reset, email address changes, and magic link sign-in. For details, see Integrating an RDS Supabase AI Application with an SMTP Server and Enabling Email Authentication.
Email authentication is built around email addresses, passwords, and email verification. Its core use cases and features include:
- Sign-up and sign-in: Users register and sign in with an email address and password.
- Email confirmation: A confirmation email is sent after sign-up to verify ownership of the email address and prevent account impersonation.
- Magic link sign-in: For passwordless sign-in, a one-time login link is sent to the user, who can sign in by clicking it.
- Password reset: Users can restore access by following a password reset link sent by email.
- Email address changes: When a user changes their registered email address, a confirmation link is sent to the new address. The change takes effect after confirmation.
- User information and session management: Users can update their email addresses or passwords, monitor authentication state changes, and sign out.
All emails for these flows are sent through SMTP. You can customize the templates in the console's Auth configuration.
- Email Sign-Up
const { data, error } = await supabase.auth.signUp({ email: 'user@example.com', // Email address password: 'your-password', // Email password })After this call, the system creates the user and sends a confirmation email. If automatic email confirmation is enabled on the console, the email address is verified immediately and the user is signed in after registration. Otherwise, the user must click the link in the confirmation email to verify the address before signing in and obtaining a session.
Prerequisites: If automatic email confirmation is disabled, sign-up depends on a configured and reachable SMTP service to send the confirmation email. If SMTP is not configured or reachable, the user will not receive the confirmation email and cannot complete sign-up.
- Email Sign-In
const { data, error } = await supabase.auth.signInWithPassword({ email: 'user@example.com', // Email address password: 'your-password', // Email password })The call returns { data, error }. Upon success, error is null and data contains the session. Upon a failure, such as when the password is incorrect or the user does not exist, error is non-null. Use the error to determine how to notify the user.
if (error) { console.error('Sign-in failed:', error.message) return } - Listen for Authentication Status Changes
A session serves as the user's credential after sign-in. The access token (JWT) has an expiration time, and the SDK automatically refreshes it before it expires, so no manual handling is required. The TOKEN_REFRESHED event is triggered when the token is refreshed.
You can listen for authentication status changes to update the user interface accordingly.
supabase.auth.onAuthStateChange((event, session) => { console.log('Authentication event:', event) console.log('Current session:', session) })Table 4 Email authentication status events Event
Description
INITIAL_SESSION
Triggered when the client initializes to restore an existing session.
SIGNED_IN
Triggered when the user signs in.
SIGNED_OUT
Triggered when the user signs out.
TOKEN_REFRESHED
Triggered when the authentication token is automatically refreshed.
PASSWORD_RECOVERY
Triggered during the password recovery workflow (when a user requests a password reset).
USER_UPDATED
Triggered when user information is updated.
- Email Address Change
const { data, error } = await supabase.auth.updateUser({ email: 'new-email@example.com' }) if (error) { console.error('Failed to change email address:', error.message) return }The user must be signed in to call updateUser(). After the call, the system sends an email change confirmation message to the new email address. The new address takes effect only after the user clicks the confirmation link. Until then, the old email address can still be used to sign in.
- Password Reset If users forget their password, they can reset it by email. First, the system sends a password reset email. After the user clicks the reset link and returns to the application, the user can set a new password.
// Send a password reset email. const { data, error } = await supabase.auth.resetPasswordForEmail( 'user@example.com', // Email address { emailRedirectTo: 'https://your-app.com/reset-password' } ) if (error) { console.error('Failed to send password reset email:', error.message) return }After the user clicks the reset link, the user is redirected back to the application, triggering the PASSWORD_RECOVERY event. The user is then in the password recovery flow and can call updateUser() on the reset page to set a new password.
// Reset the password after the user enters a new one. const { data, error } = await supabase.auth.updateUser({ password: 'new-password' }) if (error) { console.error('Failed to reset password:', error.message) return }Reset links are single-use. Email authentication must be enabled in the console's Auth configuration, and the password recovery email template must be used. A password may be rejected if it does not meet the password strength requirements. Check error information and notify the user accordingly.
- User Sign-Out
// By default, sign out the user from all devices. const { error } = await supabase.auth.signOut() // To sign out from only the current session while keeping other devices signed in, explicitly specify local. const { error } = await supabase.auth.signOut({ scope: 'local' })The default scope for signOut() is global, which signs the user out from all devices. To sign out from the current session only, explicitly pass { scope: 'local' }. Both methods trigger the SIGNED_OUT event.
- Magic Link (Passwordless Sign-In) A magic link is a passwordless email sign-in method. The user enters an email address, and the system sends an email containing a one-time login link. Clicking the link signs the user in without requiring a password. This method is suitable for applications that want to lower the barrier to registration and reduce password management overhead.
// Send a magic link email. const { data, error } = await supabase.auth.signInWithOtp({ email: 'user@example.com', // Email address options: { emailRedirectTo: 'https://your-app.com/dashboard' } }) if (error) { console.error('Failed to send sign-in link:', error.message) return }After receiving the email, the user clicks the link and is redirected back to the application. The sign-in is complete and the SIGNED_IN event is triggered. The magic link is single-use and becomes invalid after sign-in. Magic links require a configured and reachable SMTP service and use the magic link email template in the console's Auth configuration.
GitHub OAuth (SSO)
OAuth is an open authorization standard that allows users to log in to an application using an existing third-party account without setting a separate password for the application. GitHub OAuth enables third-party sign-in using a GitHub account, a flow often compared to single sign-on (SSO). Users do not need to register a separate account or set a password in the application. They can sign in by authorizing access with their existing GitHub account, which serves as a trusted identity provider. GitHub OAuth provides a complete authentication flow: sign-in → authentication status → user updates (email address and password) → sign-out.
For GitHub OAuth, a complete, runnable example guide is provided to simulate a real-world business scenario and demonstrate the end-to-end sign-in flow, from creating a GitHub OAuth App and configuring the callback URL to completing sign-in. For details, see Enabling GitHub OAuth Sign-In for an RDS Supabase AI Application.
- GitHub Sign-In When this method is called, the SDK automatically redirects the browser to GitHub for authentication and authorization. After the user approves the request on GitHub, GitHub redirects the browser to the configured callback URL with an authorization code. The application then obtains a session using this code, and the user is signed in. GitHub manages the user's credentials throughout the process, so the application never handles the user's password.
// Basic invocation const { data, error } = await supabase.auth.signInWithOAuth({ provider: 'github' }) // Specify the URL to redirect to after the callback. const { data, error } = await supabase.auth.signInWithOAuth({ provider: 'github', options: { redirectTo: 'https://your-app.com/dashboard' } })Callback addresses operate across two layers:
- Authorization callback URL for the GitHub OAuth App: the URL to which GitHub returns the authorization code to Supabase after authentication.
- redirectTo: the URL of the application page to which Supabase redirects the user after processing the authorization code, such as the page shown in the example above.
- Listen for Authentication Status Changes
supabase.auth.onAuthStateChange((event, session) => { console.log('Authentication event:', event) console.log('Current session:', session) })The listening mechanism and event list are the same as those for email authentication. For details, see Table 4.
- Email Address Change
const { data, error } = await supabase.auth.updateUser({ email: 'new-email@example.com' }) if (error) { console.error('Failed to change email address:', error.message) return }The user must be signed in to call updateUser(). After the call, the system sends an email change confirmation message to the new email address. The new address takes effect only after the user clicks the confirmation link. The procedure is the same as for email authentication.
- Password Reset
// Send a password reset email. const { data, error } = await supabase.auth.resetPasswordForEmail( 'user@example.com', // Email address { emailRedirectTo: 'https://your-app.com/reset-password' } ) if (error) { console.error('Failed to send password reset email:', error.message) return }When the user clicks the password reset link, the PASSWORD_RECOVERY event is triggered. On the password reset page, call updateUser() to set a new password. Users who sign in through GitHub SSO do not have an application password by default, so password reset can be used to set one. If they continue to sign in only with GitHub, they can skip password reset.
- User Sign-Out
const { error } = await supabase.auth.signOut()The default scope for signOut() is global, which signs the user out from all devices. To sign out from the current session only, explicitly pass { scope: 'local' }.
Reference
The following open-source Supabase documents are provided for reference only.
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot