Class Client
Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy.
public class Client : IGotrueClient<User, Session>, IGettableHeaders
- Inheritance
-
Client
- Implements
-
IGettableHeaders
- Inherited Members
Constructors
Client(ClientOptions?)
Initializes the GoTrue stateful client.
You will likely want to at least specify a
Sessions are not automatically retrieved when this object is created.
If you want to load the session from your persistence store,
If you want to load/refresh the session,
For a typical client application, you'll want to load the session from persistence and then refresh it. If your application is listening for session changes, you'll get two SignIn notifications if the persisted session is valid - one for the session loaded from disk, and a second on a successful session refresh.
public Client(ClientOptions? options = null)
Parameters
options
ClientOptions
Properties
CurrentSession
The current Session as managed by this client. Does not refresh tokens or have any other side effects.
You probably don't want to directly make changes to this object - you'll want to use other methods on this class to make changes.
public Session? CurrentSession { get; }
Property Value
CurrentUser
The currently logged in User. This is a local cache of the current session User. To persist modifications to the User you'll want to use other methods. Update(UserAttributes)>
public User? CurrentUser { get; }
Property Value
GetHeaders
Headers sent to the API on every request.
public Func<Dictionary<string, string>>? GetHeaders { get; set; }
Property Value
Online
Indicates if the client should be considered online or offline.
In a server environment, this client would likely always be online.
On a mobile client, you will want to pair this with a network implementation to turn this on and off as the device goes online and offline.
public bool Online { get; set; }
Property Value
Options
Returns the client options.
public ClientOptions Options { get; }
Property Value
TokenRefresh
Get the TokenRefresh object, if it exists
public TokenRefresh? TokenRefresh { get; }
Property Value
Methods
AddDebugListener(Action<string, Exception?>)
Add a listener to get errors that occur outside of a typical Exception flow. In particular, this is used to get errors and messages from the background thread that automatically manages refreshing the user's token.
public void AddDebugListener(Action<string, Exception?> listener)
Parameters
AddStateChangedListener(AuthEventHandler)
Adds a listener to be notified when the user state changes (e.g. the user logs in, logs out, the token is refreshed, etc).
public void AddStateChangedListener(IGotrueClient<User, Session>.AuthEventHandler authEventHandler)
Parameters
authEventHandler
IGotrueClient<User, Session>.AuthEventHandler
Challenge(MfaChallengeParams)
Prepares a challenge used to verify that a user has access to a MFA factor.
public Task<MfaChallengeResponse?> Challenge(MfaChallengeParams mfaChallengeParams)
Parameters
mfaChallengeParams
MfaChallengeParams
Returns
ChallengeAndVerify(MfaChallengeAndVerifyParams)
Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is provided by the user by entering a code seen in their authenticator app.
public Task<Session?> ChallengeAndVerify(MfaChallengeAndVerifyParams mfaChallengeAndVerifyParams)
Parameters
mfaChallengeAndVerifyParams
MfaChallengeAndVerifyParams
Returns
ClearStateChangedListeners()
Clears all of the listeners from receiving event state changes.
WARNING: The persistence handler and refresh token thread are installed as state change listeners. Clearing the listeners will also delete these handlers.
public void ClearStateChangedListeners()
Debug(string, Exception?)
Posts messages and exceptions to the debug listener. This is particularly useful for sorting out issues with the refresh token background thread.
public void Debug(string message, Exception? e = null)
Parameters
Enroll(MfaEnrollParams)
Starts the enrollment process for a new Multi-Factor Authentication (MFA)
factor. This method creates a new unverified
factor.
To verify a factor, present the QR code or secret to the user and ask them to add it to their
authenticator app.
The user has to enter the code from their authenticator app to verify it.
Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to aal2
.
public Task<MfaEnrollResponse?> Enroll(MfaEnrollParams mfaEnrollParams)
Parameters
mfaEnrollParams
MfaEnrollParams
Returns
ExchangeCodeForSession(string, string)
Logs in an existing user via a third-party provider.
public Task<Session?> ExchangeCodeForSession(string codeVerifier, string authCode)
Parameters
Returns
GetAuthenticatorAssuranceLevel()
Returns the Authenticator Assurance Level (AAL) for the active session.
aal1
(ornull
) means that the user's identity has been verified only with a conventional login (email+password, OTP, magic link, social login, etc.).aal2
means that the user's identity has been verified both with a conventional login and at least one MFA factor.
Although this method returns a promise, it's fairly quick (microseconds) and rarely uses the network. You can use this to check whether the current user needs to be shown a screen to verify their MFA factors.
public Task<MfaGetAuthenticatorAssuranceLevelResponse?> GetAuthenticatorAssuranceLevel()
Returns
GetSessionFromUrl(Uri, bool)
public Task<Session?> GetSessionFromUrl(Uri uri, bool storeSession = true)
Parameters
Returns
GetUser(string)
Get User details by JWT. Can be used to validate a JWT.
public Task<User?> GetUser(string jwt)
Parameters
jwt
stringA valid JWT. Must be a JWT that originates from a user.
Returns
LinkIdentity(Provider, SignInOptions)
Links an oauth identity to an existing user.
This method requires the PKCE flow.
public Task<ProviderAuthState> LinkIdentity(Constants.Provider provider, SignInOptions options)
Parameters
provider
Constants.ProviderProvider to Link
options
SignInOptions
Returns
ListFactors()
Returns the list of MFA factors enabled for this user
public Task<MfaListFactorsResponse?> ListFactors()
Returns
LoadSession()
Loads the session from the persistence layer.
public void LoadSession()
NotifyAuthStateChange(AuthState)
Notifies all listeners that the current user auth state has changed.
This is mainly used internally to fire notifications - most client applications won't need this.
public void NotifyAuthStateChange(Constants.AuthState stateChanged)
Parameters
Reauthenticate()
Used for re-authenticating a user in password changes.
public Task<bool> Reauthenticate()
Returns
Exceptions
RefreshSession()
Refreshes the currently logged in User's Session.
public Task<Session?> RefreshSession()
Returns
RefreshToken()
Refreshes a Token using the current session.
public Task RefreshToken()
Returns
RefreshToken(string, string)
public Task RefreshToken(string accessToken, string refreshToken)
Parameters
Returns
RemoveStateChangedListener(AuthEventHandler)
Removes a specified listener from event state changes.
public void RemoveStateChangedListener(IGotrueClient<User, Session>.AuthEventHandler authEventHandler)
Parameters
authEventHandler
IGotrueClient<User, Session>.AuthEventHandler
ResetPasswordForEmail(ResetPasswordForEmailOptions)
Sends a password reset request to an email address.
Supports the PKCE Flow (the verifier
from ResetPasswordForEmailState will be combined with ExchangeCodeForSession(string, string) in response)
public Task<ResetPasswordForEmailState> ResetPasswordForEmail(ResetPasswordForEmailOptions options)
Parameters
options
ResetPasswordForEmailOptions
Returns
ResetPasswordForEmail(string)
Sends a reset request to an email address.
public Task<bool> ResetPasswordForEmail(string email)
Parameters
email
string
Returns
RetrieveSessionAsync()
Typically called as part of the startup process for the client.
This will take the currently loaded session (e.g. from a persistence implementation) and if possible attempt to refresh it. If the loaded session is expired or invalid, it will log the user out.
public Task<Session?> RetrieveSessionAsync()
Returns
SendMagicLink(string, SignInOptions?)
Sends a Magic email login link to the specified email.
Most of the interesting configuration for this flow is done in the Supabase/GoTrue admin panel.
public Task<bool> SendMagicLink(string email, SignInOptions? options = null)
Parameters
email
stringoptions
SignInOptions
Returns
SetPersistence(IGotrueSessionPersistence<Session>)
Sets the persistence implementation for the client (e.g. file system, local storage, etc).
public void SetPersistence(IGotrueSessionPersistence<Session> persistence)
Parameters
persistence
IGotrueSessionPersistence<Session>
SetSession(string, string, bool)
Sets a new session given a user's access token and their refresh token.
- Will destroy the current session (if existing)
- Raise a SignedOut event.
- Decode token
3a. If expired (or bool
forceAccessTokenRefresh
set), force an access token refresh. 3b. If not expired, set the CurrentSession and retrieve CurrentUser from the server using theaccessToken
. - Raise a `SignedIn event if successful.
public Task<Session> SetSession(string accessToken, string refreshToken, bool forceAccessTokenRefresh = false)
Parameters
Returns
Exceptions
- GotrueException
Raised when token combination is invalid.
Settings()
Retrieves the settings from the server
public Task<Settings?> Settings()
Returns
Shutdown()
Let all of the listeners know that the stateless client is being shutdown.
In particular, the background thread that is used to refresh the token is stopped.
public void Shutdown()
SignIn(Provider, SignInOptions?)
Retrieves a ProviderAuthState to redirect to for signing in with a Constants.Provider.
This will likely be paired with a PKCE flow (set in SignInOptions) - after redirecting the user to the flow, you should pair with ExchangeCodeForSession(string, string)
public Task<ProviderAuthState> SignIn(Constants.Provider provider, SignInOptions? options = null)
Parameters
provider
Constants.Provideroptions
SignInOptions
Returns
SignIn(SignInType, string, string?, string?)
Log in an existing user, or login via a third-party provider.
public Task<Session?> SignIn(Constants.SignInType type, string identifierOrToken, string? password = null, string? scopes = null)
Parameters
type
Constants.SignInTypeType of Credentials being passed
identifierOrToken
stringAn email, phone, or RefreshToken
password
stringPassword to account (optional if
RefreshToken
)scopes
stringA space-separated list of scopes granted to the OAuth application.
Returns
SignIn(string, SignInOptions?)
Sends a magic link login email to the specified email.
public Task<bool> SignIn(string email, SignInOptions? options = null)
Parameters
email
stringoptions
SignInOptions
Returns
SignIn(string, string)
Signs in a User.
public Task<Session?> SignIn(string email, string password)
Parameters
Returns
SignInAnonymously(SignInAnonymouslyOptions?)
Creates a new anonymous user.
public Task<Session?> SignInAnonymously(SignInAnonymouslyOptions? options = null)
Parameters
options
SignInAnonymouslyOptions
Returns
SignInWithIdToken(Provider, string, string?, string?, string?)
Allows signing in with an ID token issued by certain supported providers. The [idToken] is verified for validity and a new session is established. This method of signing in only supports [Provider.Google] or [Provider.Apple].
public Task<Session?> SignInWithIdToken(Constants.Provider provider, string idToken, string? accessToken = null, string? nonce = null, string? captchaToken = null)
Parameters
provider
Constants.ProviderProvider name or OIDC
iss
value identifying which provider should be used to verify the provided token. Supported names:google
,apple
,azure
,facebook
idToken
stringOIDC ID token issued by the specified provider. The
iss
claim in the ID token must match the supplied provider. Some ID tokens contain anat_hash
which require that you provide anaccess_token
value to be accepted properly. If the token contains anonce
claim you must supply the nonce used to obtain the ID token.accessToken
stringIf the ID token contains an
at_hash
claim, then the hash of this value is compared to the value in the ID token.nonce
stringIf the ID token contains a
nonce
claim, then the hash of this value is compared to the value in the ID token.captchaToken
stringVerification token received when the user completes the captcha on the site.
Returns
Remarks
Calling this method will eliminate the current session (if any).
SignInWithOtp(SignInWithPasswordlessEmailOptions)
Log in a user using magiclink or a one-time password (OTP).
If the {{ .ConfirmationURL }}
variable is specified in the email template, a magiclink will be sent.
If the {{ .Token }}
variable is specified in the email template, an OTP will be sent.
If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
Be aware that you may get back an error message that will not distinguish between the cases where the account does not exist or, that the account can only be accessed via social login.
Do note that you will need to configure a Whatsapp sender on Twilio if you are using phone sign in with the 'whatsapp' channel. The whatsapp channel is not supported on other providers at this time.
public Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessEmailOptions options)
Parameters
Returns
Remarks
Calling this method will wipe out the current session (if any)
SignInWithOtp(SignInWithPasswordlessPhoneOptions)
Log in a user using magiclink or a one-time password (OTP).
If the {{ .ConfirmationURL }}
variable is specified in the email template, a magiclink will be sent.
If the {{ .Token }}
variable is specified in the email template, an OTP will be sent.
If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
Be aware that you may get back an error message that will not distinguish between the cases where the account does not exist or, that the account can only be accessed via social login.
Do note that you will need to configure a Whatsapp sender on Twilio if you are using phone sign in with the 'whatsapp' channel. The whatsapp channel is not supported on other providers at this time.
public Task<PasswordlessSignInState> SignInWithOtp(SignInWithPasswordlessPhoneOptions options)
Parameters
Returns
Remarks
Calling this method will wipe out the current session (if any)
SignInWithPassword(string, string)
Log in an existing user with an email and password or phone and password.
public Task<Session?> SignInWithPassword(string email, string password)
Parameters
Returns
SignInWithSSO(Guid, SignInWithSSOOptions?)
Sign in using single sign on (SSO) as supported by supabase To use SSO you need to first set up the providers using the supabase CLI please follow the guide found here: https://supabase.com/docs/guides/auth/enterprise-sso/auth-sso-saml
public Task<SSOResponse?> SignInWithSSO(Guid providerId, SignInWithSSOOptions? options = null)
Parameters
providerId
GuidThe guid of the provider you wish to use, obtained from running supabase sso list from the CLI
options
SignInWithSSOOptionsThe redirect uri and captcha token, if any
Returns
- Task<SSOResponse>
The Uri returned from supabase auth that a user can use to sign in to their given SSO provider (okta, microsoft entra, gsuite ect...)
SignInWithSSO(string, SignInWithSSOOptions?)
Sign in using single sign on (SSO) as supported by supabase To use SSO you need to first set up the providers using the supabase CLI please follow the guide found here: https://supabase.com/docs/guides/auth/enterprise-sso/auth-sso-saml
public Task<SSOResponse?> SignInWithSSO(string domain, SignInWithSSOOptions? options = null)
Parameters
domain
stringYour organizations email domain to use for sign in, this domain needs to already be registered with supabase by running the CLI commands Example:
google.com
options
SignInWithSSOOptionsThe redirect uri and captcha token, if any
Returns
- Task<SSOResponse>
The Uri returned from supabase auth that a user can use to sign in to their given SSO provider (okta, microsoft entra, gsuite ect...)
SignOut(SignOutScope)
Signs out and invalidates all sessions for a user.
public Task SignOut(Constants.SignOutScope scope = SignOutScope.Global)
Parameters
scope
Constants.SignOutScopeDetermines which sessions should be invalidated. By default, it will invalidate all session for a user
Returns
SignUp(SignUpType, string, string, SignUpOptions?)
Signs up a user
public Task<Session?> SignUp(Constants.SignUpType type, string identifier, string password, SignUpOptions? options = null)
Parameters
type
Constants.SignUpTypeidentifier
stringpassword
stringoptions
SignUpOptionsObject containing redirectTo and optional user metadata (data)
Returns
Remarks
Calling this method will log out the current user session (if any).
By default, the user needs to verify their email address before logging in. To turn this off, disable confirm email in your project. Confirm email determines if users need to confirm their email address after signing up. - If Confirm email is enabled, a user is returned but session is null. - If Confirm email is disabled, both a user and a session are returned. When the user confirms their email address, they are redirected to the SITE_URL by default. You can modify your SITE_URL or add additional redirect URLs in your project. If signUp() is called for an existing confirmed user: - If Confirm email is enabled in your project, an obfuscated/fake user object is returned. - If Confirm email is disabled, the error message, User already registered is returned. To fetch the currently logged-in user, refer to User.
SignUp(string, string, SignUpOptions?)
Signs up a user by email address.
public Task<Session?> SignUp(string email, string password, SignUpOptions? options = null)
Parameters
email
stringpassword
stringoptions
SignUpOptionsObject containing redirectTo and optional user metadata (data)
Returns
Remarks
By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
Confirm email determines if users need to confirm their email address after signing up.
- If Confirm email is enabled, a user is returned but session is null.
- If Confirm email is disabled, both a user and a session are returned.
When the user confirms their email address, they are redirected to the SITE_URL by default. You can modify your SITE_URL or
add additional redirect URLs in your project.
If signUp() is called for an existing confirmed user:
- If Confirm email is enabled in your project, an obfuscated/fake user object is returned.
- If Confirm email is disabled, the error message, User already registered is returned.
To fetch the currently logged-in user, refer to
Unenroll(MfaUnenrollParams)
Unenroll removes a MFA factor.
A user has to have an aal2
authenticator level in order to unenroll a verified
factor.
public Task<MfaUnenrollResponse?> Unenroll(MfaUnenrollParams mfaUnenrollParams)
Parameters
mfaUnenrollParams
MfaUnenrollParams
Returns
UnlinkIdentity(UserIdentity)
Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
public Task<bool> UnlinkIdentity(UserIdentity userIdentity)
Parameters
userIdentity
UserIdentityIdentity to be unlinked
Returns
Update(UserAttributes)
Updates a User.
public Task<User?> Update(UserAttributes attributes)
Parameters
attributes
UserAttributes
Returns
Verify(MfaVerifyParams)
Verifies a code against a challenge. The verification code is provided by the user by entering a code seen in their authenticator app.
public Task<Session?> Verify(MfaVerifyParams mfaVerifyParams)
Parameters
mfaVerifyParams
MfaVerifyParams
Returns
VerifyOTP(string, string, EmailOtpType)
Log in a user give a user supplied OTP received via email.
public Task<Session?> VerifyOTP(string email, string token, Constants.EmailOtpType type = EmailOtpType.MagicLink)
Parameters
email
stringtoken
stringtype
Constants.EmailOtpTypeDefaults to MagicLink
Returns
VerifyOTP(string, string, MobileOtpType)
Log in a user given a User supplied OTP received via mobile.
public Task<Session?> VerifyOTP(string phone, string token, Constants.MobileOtpType type = MobileOtpType.SMS)
Parameters
phone
stringThe user's phone number.
token
stringToken sent to the user's phone.
type
Constants.MobileOtpTypeSMS or phone change
Returns
VerifyTokenHash(string, EmailOtpType)
Log in a user given the token hash used in an email confirmation link.
public Task<Session?> VerifyTokenHash(string tokenHash, Constants.EmailOtpType type = EmailOtpType.Email)
Parameters
tokenHash
stringtype
Constants.EmailOtpType