Skip to main content

AuthClient

Struct AuthClient 

Source
pub struct AuthClient { /* private fields */ }
Expand description

HTTP client for Supabase GoTrue auth API.

Communicates with GoTrue REST endpoints at /auth/v1/.... Provides built-in session state management, event broadcasting, and optional automatic token refresh.

§Example

use supabase_client_auth::AuthClient;

let auth = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;
let session = auth.sign_in_with_password_email("user@example.com", "password").await?;

// Session is automatically stored — retrieve it later:
let stored = auth.get_session().await;

// Subscribe to auth state changes:
let mut sub = auth.on_auth_state_change();

Implementations§

Source§

impl AuthClient

Source

pub fn new(supabase_url: &str, api_key: &str) -> Result<Self, AuthError>

Create a new auth client.

supabase_url is the project URL (e.g., https://your-project.supabase.co). api_key is the Supabase anon key, sent as the apikey header.

Source

pub fn base_url(&self) -> &Url

Get the base URL for the auth API.

Source

pub async fn get_session(&self) -> Option<Session>

Get the currently stored session (no network call).

Returns None if no session has been stored (e.g., user hasn’t signed in yet).

Source

pub async fn set_session(&self, session: Session)

Set/replace the stored session and emit SignedIn.

Use this to restore a session from external storage (e.g., persisted tokens).

Source

pub async fn clear_session(&self)

Clear the stored session and emit SignedOut.

This is a local operation — it does NOT call GoTrue /logout. Use sign_out_current() to also invalidate server-side.

Source

pub fn on_auth_state_change(&self) -> AuthSubscription

Subscribe to auth state change events.

Returns an AuthSubscription that receives events via next(). Multiple subscriptions can be active simultaneously.

Source

pub fn start_auto_refresh(&self)

Start automatic token refresh with default configuration.

Spawns a background task that checks the stored session periodically and refreshes it before expiry.

Source

pub fn start_auto_refresh_with(&self, config: AutoRefreshConfig)

Start automatic token refresh with custom configuration.

Source

pub fn stop_auto_refresh(&self)

Stop automatic token refresh.

Source

pub async fn get_session_user(&self) -> Result<User, AuthError>

Get the user from the stored session (calls GoTrue /user).

Returns AuthError::NoSession if no session is stored.

Source

pub async fn refresh_current_session(&self) -> Result<Session, AuthError>

Refresh the stored session using its refresh_token.

Returns AuthError::NoSession if no session is stored.

Source

pub async fn sign_out_current(&self) -> Result<(), AuthError>

Sign out using the stored session’s access_token, then clear session.

Returns AuthError::NoSession if no session is stored.

Source

pub async fn sign_out_current_with_scope( &self, scope: SignOutScope, ) -> Result<(), AuthError>

Sign out with scope using the stored session’s access_token.

Returns AuthError::NoSession if no session is stored.

Source

pub async fn sign_up_with_email( &self, email: &str, password: &str, ) -> Result<AuthResponse, AuthError>

Sign up a new user with email and password.

Mirrors supabase.auth.signUp({ email, password }). If the response includes a session, it is stored and SignedIn is emitted.

Source

pub async fn sign_up_with_email_and_data( &self, email: &str, password: &str, data: Option<JsonValue>, ) -> Result<AuthResponse, AuthError>

Sign up a new user with email, password, and custom user metadata.

Mirrors supabase.auth.signUp({ email, password, options: { data } }). If the response includes a session, it is stored and SignedIn is emitted.

Source

pub async fn sign_up_with_phone( &self, phone: &str, password: &str, ) -> Result<AuthResponse, AuthError>

Sign up a new user with phone and password.

Mirrors supabase.auth.signUp({ phone, password }). If the response includes a session, it is stored and SignedIn is emitted.

Source

pub async fn sign_in_with_password_email( &self, email: &str, password: &str, ) -> Result<Session, AuthError>

Sign in with email and password.

Mirrors supabase.auth.signInWithPassword({ email, password }). Stores the session and emits SignedIn.

Source

pub async fn sign_in_with_password_phone( &self, phone: &str, password: &str, ) -> Result<Session, AuthError>

Sign in with phone and password.

Mirrors supabase.auth.signInWithPassword({ phone, password }). Stores the session and emits SignedIn.

Source

pub async fn sign_in_with_otp_email(&self, email: &str) -> Result<(), AuthError>

Send a magic link / OTP to an email address.

Mirrors supabase.auth.signInWithOtp({ email }).

Source

pub async fn sign_in_with_otp_phone( &self, phone: &str, channel: OtpChannel, ) -> Result<(), AuthError>

Send an OTP to a phone number.

Mirrors supabase.auth.signInWithOtp({ phone, options: { channel } }).

Source

pub async fn verify_otp( &self, params: VerifyOtpParams, ) -> Result<Session, AuthError>

Verify an OTP token.

Mirrors supabase.auth.verifyOtp(params). Stores the session and emits SignedIn.

Source

pub async fn sign_in_anonymous(&self) -> Result<Session, AuthError>

Sign in anonymously, creating a new anonymous user.

Mirrors supabase.auth.signInAnonymously(). Stores the session and emits SignedIn.

Source

pub fn get_oauth_sign_in_url( &self, provider: OAuthProvider, redirect_to: Option<&str>, scopes: Option<&str>, ) -> Result<String, AuthError>

Build the OAuth sign-in URL for a given provider.

Returns the URL to redirect the user to. This does not make a network request.

Mirrors supabase.auth.signInWithOAuth({ provider, options }).

Source

pub async fn exchange_code_for_session( &self, code: &str, code_verifier: Option<&str>, ) -> Result<Session, AuthError>

Exchange an auth code (from PKCE flow) for a session.

Mirrors supabase.auth.exchangeCodeForSession(authCode). Stores the session and emits SignedIn.

Source

pub async fn refresh_session( &self, refresh_token: &str, ) -> Result<Session, AuthError>

Refresh a session using a refresh token.

Mirrors supabase.auth.refreshSession(). Stores the new session and emits TokenRefreshed.

Source

pub async fn get_user(&self, access_token: &str) -> Result<User, AuthError>

Get the user associated with an access token.

Makes a network request to GoTrue to validate the token and fetch the user.

Mirrors supabase.auth.getUser(jwt?).

Source

pub async fn update_user( &self, access_token: &str, params: UpdateUserParams, ) -> Result<User, AuthError>

Update the current user’s attributes.

Mirrors supabase.auth.updateUser(attributes). Emits UserUpdated and updates the user in the stored session (if any).

Source

pub async fn sign_out(&self, access_token: &str) -> Result<(), AuthError>

Sign out the user (global scope by default).

Mirrors supabase.auth.signOut(). Clears the stored session and emits SignedOut.

Source

pub async fn sign_out_with_scope( &self, access_token: &str, scope: SignOutScope, ) -> Result<(), AuthError>

Sign out with a specific scope.

Mirrors supabase.auth.signOut({ scope }). Clears the stored session and emits SignedOut.

Source

pub async fn reset_password_for_email( &self, email: &str, redirect_to: Option<&str>, ) -> Result<(), AuthError>

Send a password reset email.

Mirrors supabase.auth.resetPasswordForEmail(email, options).

Source

pub fn admin(&self) -> AdminClient<'_>

Create an admin client using the current API key as the service role key.

The API key must be a service_role key for admin operations to work.

Mirrors supabase.auth.admin.

Source

pub fn admin_with_key<'a>( &'a self, service_role_key: &'a str, ) -> AdminClient<'a>

Create an admin client with an explicit service role key.

Source

pub async fn mfa_enroll( &self, access_token: &str, params: MfaEnrollParams, ) -> Result<MfaEnrollResponse, AuthError>

Enroll a new MFA factor (TOTP or phone).

Mirrors supabase.auth.mfa.enroll().

Source

pub async fn mfa_challenge( &self, access_token: &str, factor_id: &str, ) -> Result<MfaChallengeResponse, AuthError>

Create a challenge for an enrolled factor.

Mirrors supabase.auth.mfa.challenge().

Source

pub async fn mfa_challenge_with_params( &self, access_token: &str, factor_id: &str, params: MfaChallengeParams, ) -> Result<MfaChallengeResponse, AuthError>

Create a challenge for an enrolled factor with additional params.

The params can specify the channel (sms/whatsapp) for phone factors.

Source

pub async fn mfa_verify( &self, access_token: &str, factor_id: &str, params: MfaVerifyParams, ) -> Result<Session, AuthError>

Verify an MFA challenge with a TOTP/SMS code. Returns a new AAL2 session.

Mirrors supabase.auth.mfa.verify(). Stores the session and emits SignedIn.

Source

pub async fn mfa_challenge_and_verify( &self, access_token: &str, factor_id: &str, code: &str, ) -> Result<Session, AuthError>

Combined challenge + verify for TOTP factors (convenience).

Mirrors supabase.auth.mfa.challengeAndVerify(). Stores the session and emits SignedIn.

Source

pub async fn mfa_unenroll( &self, access_token: &str, factor_id: &str, ) -> Result<MfaUnenrollResponse, AuthError>

Unenroll (delete) an MFA factor.

Mirrors supabase.auth.mfa.unenroll().

Source

pub async fn mfa_list_factors( &self, access_token: &str, ) -> Result<MfaListFactorsResponse, AuthError>

List the user’s enrolled MFA factors, categorized by type.

Fetches the user object and categorizes its factors.

Mirrors supabase.auth.mfa.listFactors().

Source

pub async fn mfa_get_authenticator_assurance_level( &self, access_token: &str, ) -> Result<AuthenticatorAssuranceLevelInfo, AuthError>

Get the user’s authenticator assurance level.

Fetches the user object and inspects factors to determine AAL.

Mirrors supabase.auth.mfa.getAuthenticatorAssuranceLevel().

Source

pub async fn sign_in_with_sso( &self, params: SsoSignInParams, ) -> Result<SsoSignInResponse, AuthError>

Sign in with enterprise SAML SSO.

Mirrors supabase.auth.signInWithSSO().

Source

pub async fn sign_in_with_id_token( &self, params: SignInWithIdTokenParams, ) -> Result<Session, AuthError>

Sign in with an external OIDC ID token (e.g., from Google/Apple mobile SDK).

Mirrors supabase.auth.signInWithIdToken(). Stores the session and emits SignedIn.

Link an OAuth provider identity to the current user.

Returns a URL to redirect the user to for OAuth authorization.

Mirrors supabase.auth.linkIdentity().

Unlink an identity from the current user.

Mirrors supabase.auth.unlinkIdentity().

Source

pub async fn resend(&self, params: ResendParams) -> Result<(), AuthError>

Resend an OTP or confirmation email/SMS.

Mirrors supabase.auth.resend().

Source

pub async fn reauthenticate(&self, access_token: &str) -> Result<(), AuthError>

Send a reauthentication nonce to the user’s verified email/phone.

The nonce is used via the nonce field in update_user().

Mirrors supabase.auth.reauthenticate().

Source

pub async fn get_user_identities( &self, access_token: &str, ) -> Result<Vec<Identity>, AuthError>

Get the identities linked to the current user.

Convenience method that calls get_user() and returns the identities field.

Mirrors supabase.auth.getUserIdentities().

Source

pub async fn oauth_get_authorization_details( &self, access_token: &str, authorization_id: &str, ) -> Result<OAuthAuthorizationDetailsResponse, AuthError>

Get authorization details for an OAuth authorization request.

Returns either full details (user must consent) or a redirect (already consented).

Mirrors supabase.auth.oauth.getAuthorizationDetails().

Source

pub async fn oauth_approve_authorization( &self, access_token: &str, authorization_id: &str, ) -> Result<OAuthRedirect, AuthError>

Approve an OAuth authorization request.

Mirrors supabase.auth.oauth.approveAuthorization().

Source

pub async fn oauth_deny_authorization( &self, access_token: &str, authorization_id: &str, ) -> Result<OAuthRedirect, AuthError>

Deny an OAuth authorization request.

Mirrors supabase.auth.oauth.denyAuthorization().

Source

pub async fn oauth_list_grants( &self, access_token: &str, ) -> Result<Vec<OAuthGrant>, AuthError>

List all OAuth grants (permissions) for the current user.

Mirrors supabase.auth.oauth.listGrants().

Source

pub async fn oauth_revoke_grant( &self, access_token: &str, client_id: &str, ) -> Result<(), AuthError>

Revoke an OAuth grant for a specific client.

Mirrors supabase.auth.oauth.revokeGrant().

Source

pub fn generate_pkce_pair() -> PkcePair

Generate a PKCE (Proof Key for Code Exchange) verifier/challenge pair.

Uses S256 method: the challenge is BASE64URL(SHA256(verifier)). The verifier is 43 URL-safe random characters.

Source

pub fn build_oauth_authorize_url( &self, params: &OAuthAuthorizeUrlParams, ) -> String

Build an OAuth authorization URL for the authorization code flow.

Returns a URL to redirect the user to. This does not make a network request.

Source

pub async fn oauth_token_exchange( &self, params: OAuthTokenExchangeParams, ) -> Result<OAuthTokenResponse, AuthError>

Exchange an authorization code for tokens.

POST to /oauth/token with grant_type=authorization_code. Uses application/x-www-form-urlencoded as per OAuth 2.1 spec.

Source

pub async fn oauth_token_refresh( &self, client_id: &str, refresh_token: &str, client_secret: Option<&str>, ) -> Result<OAuthTokenResponse, AuthError>

Refresh an OAuth token.

POST to /oauth/token with grant_type=refresh_token.

Source

pub async fn oauth_revoke_token( &self, token: &str, token_type_hint: Option<&str>, ) -> Result<(), AuthError>

Revoke an OAuth token.

POST to /oauth/revoke.

Source

pub async fn oauth_get_openid_configuration( &self, ) -> Result<OpenIdConfiguration, AuthError>

Fetch the OpenID Connect discovery document.

GET /.well-known/openid-configuration.

Source

pub async fn oauth_get_jwks(&self) -> Result<JwksResponse, AuthError>

Fetch the JSON Web Key Set (JWKS) for token verification.

GET /.well-known/jwks.json.

Source

pub async fn oauth_get_userinfo( &self, access_token: &str, ) -> Result<JsonValue, AuthError>

Fetch user info from the OAuth userinfo endpoint.

GET /oauth/userinfo with Bearer token.

Source

pub fn get_claims(token: &str) -> Result<JsonValue, AuthError>

Extract claims from a JWT access token without verifying the signature.

This is a client-side decode only — it does NOT validate the token. Useful for reading sub, exp, role, email, custom claims, etc.

Returns the payload as a serde_json::Value object.

Source

pub async fn sign_up_with_email_full( &self, email: &str, password: &str, data: Option<JsonValue>, captcha_token: Option<&str>, ) -> Result<AuthResponse, AuthError>

Sign up with email, password, optional user data, and optional captcha token.

This is the full-featured sign-up method that consolidates email sign-up with all optional parameters. The captcha token is sent as gotrue_meta_security.captcha_token in the request body.

Source

pub async fn sign_in_with_password_email_captcha( &self, email: &str, password: &str, captcha_token: Option<&str>, ) -> Result<Session, AuthError>

Sign in with email and password, with an optional captcha token.

Source

pub async fn sign_in_with_otp_email_captcha( &self, email: &str, captcha_token: Option<&str>, ) -> Result<(), AuthError>

Send a magic link / OTP to an email, with an optional captcha token.

Source

pub async fn sign_in_with_otp_phone_captcha( &self, phone: &str, channel: OtpChannel, captcha_token: Option<&str>, ) -> Result<(), AuthError>

Send an OTP to a phone number, with an optional captcha token.

Source

pub async fn sign_in_with_web3( &self, params: Web3SignInParams, ) -> Result<Session, AuthError>

Sign in with a Web3 wallet (Ethereum or Solana).

POST to /token?grant_type=web3 with chain, address, message, signature, nonce. Stores the session and emits SignedIn.

Trait Implementations§

Source§

impl Clone for AuthClient

Source§

fn clone(&self) -> AuthClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AuthClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more