Skip to main content

Authentication

signUp​

Future<SignUpRes> auth.signUp(SignUpReq params)

Register a new user account using smart registration and login flow.

  • Creates a new user account
  • Uses smart registration and login flow: send verification code → wait for user input → smart judgment of user existence → auto login or register and login
  • If user already exists, directly login; if user does not exist, register new user and auto login

Parameters

params
SignUpReq

Response

Future
SignUpRes

Example

final result = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'securePassword123',
nickname: 'New User',
));

if (result.error != null) {
print('Registration failed: ${result.error!.message}');
return;
}

// Verify verification code
final verifyResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);

if (verifyResult.isSuccess) {
print('Registration successful: ${verifyResult.data?.user?.id}');
}

signInAnonymously​

Future<SignInRes> auth.signInAnonymously({String? providerToken})

Anonymous login, creates a temporary anonymous user account.

  • Creates a temporary anonymous user account
  • No identity verification info needed
  • Suitable for scenarios requiring temporary access

Parameters

providerToken
String?

Third-party platform token, used to associate third-party platform identity

Response

Future
SignInRes

Example

final result = await auth.signInAnonymously();

if (result.isSuccess) {
print('Anonymous login successful');
print('User ID: ${result.data?.user?.id}');
print('Is anonymous: ${result.data?.user?.isAnonymous}');
} else {
print('Anonymous login failed: ${result.error!.message}');
}

signInWithPassword​

Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)

Login with password. Supports login via username, email, or phone number.

Parameters

params
SignInWithPasswordReq

Response

Future
SignInRes

Example

final result = await auth.signInWithPassword(
SignInWithPasswordReq(
email: 'user@example.com',
password: 'securePassword123',
),
);

if (result.isSuccess) {
print('Login successful: ${result.data?.user?.id}');
} else {
print('Login failed: ${result.error!.message}');
}

signInWithUsername​

Future<SignInRes> auth.signInWithUsername({
required VerificationInfo verificationInfo,
required String verificationCode,
required String username,
String? loginType,
dynamic bindInfo,
})

Sign in with username/email/phone and a verification code. Typically call getVerification first to send the code, then pass the returned verification info and the user-entered code to this method.

  • If verificationInfo.isUser is true, the existing user is signed in
  • If the user does not exist, a new account is registered and signed in
  • Use bindInfo to link a third-party identity during sign-in or sign-up

Parameters

verificationInfo
VerificationInfo

Verification info, usually from the getVerification response

verificationCode
String

Verification code entered by the user

username
String

Username, email, or phone number

loginType
String?

Login type: email or phone. Treated as email when set to email; otherwise treated as a phone number (automatically prefixed with +86)

bindInfo
dynamic

Third-party identity binding info, e.g. {'providerToken': '...'} or {'providerId': '...'}

Response

Future
SignInRes

Example

final verification = await auth.getVerification(email: 'user@example.com');

if (verification.error != null) {
print('Failed to send verification code: ${verification.error!.message}');
return;
}

final result = await auth.signInWithUsername(
verificationInfo: VerificationInfo(
verificationId: verification.data!.verificationId,
isUser: verification.data!.isUser,
),
verificationCode: '123456',
username: 'user@example.com',
loginType: 'email',
);

if (result.isSuccess) {
print('Login successful: ${result.data?.user?.id}');
} else {
print('Login failed: ${result.error!.message}');
}

signInWithOtp​

Future<SignInWithOtpRes> auth.signInWithOtp(SignInWithOtpReq params)

Login with OTP (one-time verification code). After calling, a verification code will be sent. You need to complete verification through the returned verifyOtp callback.

  • If the user does not exist, a user will be created by default. You can control whether to automatically create a user with the shouldCreateUser parameter (default is true)

Parameters

params
SignInWithOtpReq

Response

Future
SignInWithOtpRes

Example

final result = await auth.signInWithOtp(
SignInWithOtpReq(email: 'user@example.com'),
);

if (result.error != null) {
print('Failed to send verification code: ${result.error!.message}');
return;
}

// Call after user inputs verification code
final loginResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);

if (loginResult.isSuccess) {
print('OTP login successful: ${loginResult.data?.user?.id}');
}

signInWithOAuth​

Future<SignInOAuthRes> auth.signInWithOAuth(SignInWithOAuthReq params)

Login with OAuth third-party platform. Returns authorization URL, you need to guide the user to redirect to this URL to complete authorization.

Parameters

params
SignInWithOAuthReq

Response

Future
SignInOAuthRes

Example

final result = await auth.signInWithOAuth(
SignInWithOAuthReq(provider: 'wechat'),
);

if (result.isSuccess) {
final authUrl = result.data!.url!;
print('Please redirect to authorization page: $authUrl');
// Guide user to open authUrl for authorization
}

signInWithIdToken​

Future<SignInRes> auth.signInWithIdToken(SignInWithIdTokenReq params)

Sign in with a third-party identity token (IdToken), for scenarios where you already have a WeChat, Google, or similar platform token. The SDK sends provider as provider_id and token as provider_id_token to the sign-in API.

Parameters

params
SignInWithIdTokenReq

Response

Future
SignInRes

Example

final result = await auth.signInWithIdToken(
SignInWithIdTokenReq(
token: 'provider-id-token',
provider: 'wechat',
),
);

if (result.isSuccess) {
print('IdToken login successful: ${result.data?.user?.id}');
} else {
print('Login failed: ${result.error!.message}');
}

signInWithCustomTicket​

Future<SignInRes> auth.signInWithCustomTicket(Future<String> Function() getTicketFn)

Login with custom ticket. By passing an async function to get the ticket, the server generates the ticket and completes the login.

Parameters

getTicketFn
Future<String> Function()

Async function to get custom login ticket

Response

Future
SignInRes

Example

final result = await auth.signInWithCustomTicket(() async {
// Get custom ticket from your server
final ticket = await fetchTicketFromServer();
return ticket;
});

if (result.isSuccess) {
print('Custom ticket login successful: ${result.data?.user?.id}');
} else {
print('Login failed: ${result.error!.message}');
}

Session Management​

getSession​

Future<SignInRes> auth.getSession();

Get current session. If token has expired, it will be automatically refreshed.

Parameters

No parameters

Response

Future
SignInRes

Example

final result = await auth.getSession();

if (result.isSuccess) {
final session = result.data?.session;
print('Access Token: ${session?.accessToken}');
print('User: ${result.data?.user?.id}');
} else {
print('Failed to get session: ${result.error!.message}');
}

refreshSession​

Future<SignInRes> auth.refreshSession([String? refreshToken])

Refresh session. Use Refresh Token to get a new Access Token.

Parameters

refreshToken
String?

Refresh token (optional, defaults to current session's refreshToken)

Response

Future
SignInRes

Example

final result = await auth.refreshSession();

if (result.isSuccess) {
print('Session refreshed');
print('New Access Token: ${result.data?.session?.accessToken}');
} else {
print('Refresh failed: ${result.error!.message}');
}

setSession​

Future<SignInRes> auth.setSession(SetSessionReq params)

Set session. Restore session state with Refresh Token.

Parameters

params
SetSessionReq

Response

Future
SignInRes

Example

final result = await auth.setSession(
SetSessionReq(refreshToken: 'your-refresh-token'),
);

if (result.isSuccess) {
print('Session set successfully: ${result.data?.user?.id}');
}

signOut​

Future<SignOutRes> auth.signOut([SignOutReq? params])

Sign out. Revoke the current access token and clear the local session. params is not sent to the server.

Parameters

params
SignOutReq?

Logout configuration options (optional)

Response

Future
SignOutRes

Example

await auth.signOut();
print("Logged out");

onAuthStateChange​

OnAuthStateChangeResult auth.onAuthStateChange(OnAuthStateChangeCallback callback)

Listen for authentication state changes. Supports listening for login, logout, token refresh, and user update events.

Parameters

callback
void Function(AuthStateChangeEvent, Session?, AuthStateChangeInfo?)

State change callback function

Response

OnAuthStateChangeResult
OnAuthStateChangeResult

Example

final result = auth.onAuthStateChange((event, session, info) {
print('Auth state changed: ${event.value}');
if (session != null) {
print('User: ${session.user?.id}');
}
});

// Stop listening
result.data?.subscription.unsubscribe();

getClaims​

Future<GetClaimsRes> auth.getClaims();

Get JWT Claims of current Access Token (token claims).

Parameters

No parameters

Response

Future
GetClaimsRes

Example

final result = await auth.getClaims();

if (result.isSuccess) {
final claims = result.data?.claims;
print('User ID: ${claims?.sub}');
print('Email: ${claims?.email}');
print('User groups: ${claims?.groups}');
print('Expiration: ${claims?.exp}');
}

User Management​

getUser​

Future<GetUserRes> auth.getUser();

Get current logged-in user info.

Parameters

No parameters

Response

Future
GetUserRes

Example

final result = await auth.getUser();

if (result.isSuccess) {
final user = result.data?.user;
print('User ID: ${user?.id}');
print('Email: ${user?.email}');
print('Nickname: ${user?.userMetadata?.nickName}');
} else {
print('Failed to get user info: ${result.error!.message}');
}

refreshUser​

Future<SignInRes> auth.refreshUser();

Refresh user info. Re-fetch the latest user data from server and update local session.

Parameters

No parameters

Response

Future
SignInRes

Example

final result = await auth.refreshUser();

if (result.isSuccess) {
print('User info refreshed: ${result.data?.user?.id}');
}

updateUser​

Future<UpdateUserRes> auth.updateUser(UpdateUserReq params)

Update user info. If updating email or phone number, verification code verification is required.

Parameters

params
UpdateUserReq

Response

Future
UpdateUserRes

Example

final result = await auth.updateUser(
UpdateUserReq(nickname: 'New Nickname', avatarUrl: 'https://example.com/avatar.png'),
);

if (result.isSuccess) {
print('User info updated: ${result.data?.user?.userMetadata?.nickName}');
}

deleteUser​

Future<CloudBaseResponse<void>> auth.deleteUser(DeleteUserReq params)

Delete current user. Password is required for security verification.

Parameters

params
DeleteUserReq

Response

Future
CloudBaseResponse<void>

Example

final result = await auth.deleteUser(
DeleteUserReq(password: 'currentPassword'),
);

if (result.isSuccess) {
print('User deleted');
} else {
print('Deletion failed: ${result.error!.message}');
}

Identity Source Management​

getUserIdentities​

Future<GetUserIdentitiesRes> auth.getUserIdentities();

Get the list of identity sources bound to the current user.

Parameters

No parameters

Response

Future
GetUserIdentitiesRes

Example

final result = await auth.getUserIdentities();

if (result.isSuccess) {
for (final identity in result.data?.identities ?? []) {
print('Identity: ${identity.name} (${identity.provider})');
}
}

linkIdentity​

Future<LinkIdentityRes> auth.linkIdentity(LinkIdentityReq params)

Bind third-party identity source. Will redirect to third-party authorization page to complete binding.

Parameters

params
LinkIdentityReq

Response

Future
LinkIdentityRes

Example

final result = await auth.linkIdentity(
LinkIdentityReq(provider: 'wechat'),
);

if (result.isSuccess) {
print('Authorization URL: ${result.data?.url}');
}

unlinkIdentity​

Future<CloudBaseResponse<void>> auth.unlinkIdentity(UnlinkIdentityReq params)

Unbind third-party identity source.

Parameters

params
UnlinkIdentityReq

Response

Future
CloudBaseResponse<void>

Example

final result = await auth.unlinkIdentity(
UnlinkIdentityReq(provider: 'wechat'),
);

if (result.isSuccess) {
print('Identity source unbound');
}

Password Management​

resetPasswordForEmail​

Future<ResetPasswordForEmailRes> auth.resetPasswordForEmail(String emailOrPhone, {String? redirectTo})

Reset password via email or phone number. After calling, a verification code will be sent. You need to complete password reset through the returned updateUser callback.

Parameters

emailOrPhone
String

Email or phone number

redirectTo
String?

Redirect URL

Response

Future
ResetPasswordForEmailRes

Example

final result = await auth.resetPasswordForEmail('user@example.com');

if (result.error != null) {
print('Failed to send verification code: ${result.error!.message}');
return;
}

// After user receives verification code
final resetResult = await result.data!.updateUser!(
UpdateUserAttributes(nonce: '123456', password: 'newPassword123'),
);

if (resetResult.isSuccess) {
print('Password reset successfully, auto-logged in');
}

resetPasswordForOld​

Future<SignInRes> auth.resetPasswordForOld(ResetPasswordForOldReq params)

Reset password with old password.

Parameters

params
ResetPasswordForOldReq

Response

Future
SignInRes

Example

final result = await auth.resetPasswordForOld(
ResetPasswordForOldReq(
oldPassword: 'oldPassword123',
newPassword: 'newPassword456',
),
);

if (result.isSuccess) {
print('Password changed successfully');
} else {
print('Password change failed: ${result.error!.message}');
}

reauthenticate​

Future<ReauthenticateRes> auth.reauthenticate();

Re-authenticate. Send verification code to user's email or phone number. After verification, sensitive operations can be performed (such as setting a new password).

Parameters

No parameters

Response

Future
ReauthenticateRes

Example

final result = await auth.reauthenticate();

if (result.error != null) {
print('Failed to send verification code: ${result.error!.message}');
return;
}

final authResult = await result.data!.updateUser!(
UpdateUserAttributes(nonce: '123456', password: 'newSecurePassword'),
);

if (authResult.isSuccess) {
print('Re-authentication successful');
}

Verification Management​

getVerification​

Future<CloudBaseResponse<GetVerificationResData>> auth.getVerification({String? email, String? phoneNumber})

Send a verification code to an email address or phone number.

Parameters

email
String?

Email (one of email or phoneNumber)

phoneNumber
String?

Phone number (one of email or phoneNumber)

Response

Future
CloudBaseResponse<GetVerificationResData>

Example

final result = await auth.getVerification(email: 'user@example.com');

if (result.isSuccess) {
print('Verification code sent, verification ID: ${result.data?.verificationId}');
print('Existing user: ${result.data?.isUser}');
}

verify​

Future<CloudBaseResponse<VerifyCodeResData>> auth.verify({required String verificationId, required String verificationCode})

Verify a verification code.

Parameters

verificationId
String

Verification ID

verificationCode
String

Verification code

Response

Future
CloudBaseResponse<VerifyCodeResData>

Example

final result = await auth.verify(
verificationId: 'verification-id',
verificationCode: '123456',
);

if (result.isSuccess) {
print('Verification succeeded, token: ${result.data?.verificationToken}');
}

verifyOAuth​

Future<VerifyOAuthRes> auth.verifyOAuth([VerifyOAuthReq? params])

Verify the OAuth callback to finish third-party sign-in or identity binding. When params is omitted, code and state are read from the current page URL.

Parameters

params
VerifyOAuthReq?

OAuth callback params (optional; read from the URL when omitted)

Response

Future
VerifyOAuthRes

Example

// Read code and state from the URL
final result = await auth.verifyOAuth();

if (result.isSuccess) {
print('OAuth verification succeeded: ${result.data?.user?.id}');
}

// Pass params explicitly
final result2 = await auth.verifyOAuth(VerifyOAuthReq(
code: 'authorization-code',
state: 'state-value',
provider: 'google',
redirectUri: 'https://example.com/callback',
));

verifyOtp​

Future<SignInRes> auth.verifyOtp(VerifyOtpReq params)

Verify the OTP and sign in.

Parameters

params
VerifyOtpReq

Response

Future
SignInRes

Example

final result = await auth.verifyOtp(VerifyOtpReq(
email: 'user@example.com',
token: '123456',
messageId: 'message-id',
));

if (result.isSuccess) {
print('Verification and sign-in succeeded: ${result.data?.user?.id}');
}

resend​

Future<ResendRes> auth.resend(ResendReq params)

Resend verification code.

Parameters

params
ResendReq

Response

Future
ResendRes

Example

final result = await auth.resend(
ResendReq(email: 'user@example.com', type: ResendType.signup),
);

if (result.isSuccess) {
print('Verification code resent, message ID: ${result.data?.messageId}');
}

getCaptchaToken​

Future<String?> app.captcha.getCaptchaToken({bool forceNew = false, required String state})

Get a valid CAPTCHA token. One is required after repeated password errors or frequent verification-code requests. The SDK reads the cache first. If the cache is empty, it creates a CAPTCHA and opens the verification UI. A custom handler or the built-in dialog can be used.

Parameters

forceNew
bool

Force a new CAPTCHA (default false)

state
String

State identifier

Response

Future
String?

CAPTCHA token, null on failure

Example

// Set navigatorKey during initialization
final navigatorKey = GlobalKey<NavigatorState>();

final app = await CloudBase.init(
env: 'your-env-id',
captchaConfig: CaptchaConfig(navigatorKey: navigatorKey),
);

// Get a CAPTCHA token (opens the CAPTCHA dialog)
final token = await app.captcha.getCaptchaToken(state: 'login');
print('Captcha Token: $token');

appendCaptchaTokenToUrl​

Future<String> app.captcha.appendCaptchaTokenToUrl(
String url, {
required String state,
bool forceNew = false,
})

Get a CAPTCHA token and append it to the URL. Returns the original URL when no token is available.

Parameters

url
String

Original URL

state
String

State identifier

forceNew
bool

Force a new CAPTCHA. Default is false

Response

Future
String

URL with captcha_token, or the original URL when no token is available

Example

final url = await app.captcha.appendCaptchaTokenToUrl(
'https://example.com/callback',
state: 'login',
);

createCaptchaData​

Future<CreateCaptchaDataRes> app.captcha.createCaptchaData({required String state})

Create CAPTCHA data. Returns the CAPTCHA image data and token.

Parameters

state
String

State identifier

Response

Future
CreateCaptchaDataRes

Example

final captchaData = await app.captcha.createCaptchaData(state: 'login');
print('CAPTCHA image: ${captchaData.data}');
print('Token: ${captchaData.token}');

verifyCaptchaData​

Future<VerifyCaptchaRes> app.captcha.verifyCaptchaData({required String token, required String key})

Verify the CAPTCHA entered by the user.

Parameters

token
String

CAPTCHA token

key
String

CAPTCHA entered by the user

Response

Future
VerifyCaptchaRes

Example

final result = await app.captcha.verifyCaptchaData(
token: captchaData.token,
key: 'CAPTCHA entered by the user',
);
print('CAPTCHA token: ${result.captchaToken}');

clearCaptchaToken​

Future<void> app.captcha.clearCaptchaToken()

Clear the CAPTCHA token cached locally.

Parameters

No parameters

Response

Future
void

No return value

Example

await app.captcha.clearCaptchaToken();
print('CAPTCHA token cleared');