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
Response
Example
- Email Registration
- Phone Registration
- Error Handling
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}');
}
final result = await auth.signUp(SignUpReq(
phone: '13800138000',
password: 'securePassword123',
));
if (result.error != null) {
print('Failed to send verification code: ${result.error!.message}');
return;
}
final verifyResult = await result.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Registration successful: ${verifyResult.data?.user?.phone}');
}
final result = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'password123',
));
if (result.error != null) {
final code = result.error!.code;
switch (code) {
case 'already_exists':
print('Email already registered');
break;
case 'password_too_weak':
print('Password too weak');
break;
case 'invalid_email':
print('Invalid email format');
break;
default:
print('Registration failed: ${result.error!.message}');
}
}
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
Third-party platform token, used to associate third-party platform identity
Response
Example
- Anonymous Login
- Anonymous User Upgrade Flow
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}');
}
// Step 1: Anonymous login
final anonymousResult = await auth.signInAnonymously();
if (anonymousResult.error != null) {
print('Anonymous login failed: ${anonymousResult.error!.message}');
return;
}
print('Anonymous login successful, preparing to upgrade to official user');
// Step 2: Bind email (pass anonymousToken during registration)
final upgradeResult = await auth.signUp(SignUpReq(
email: 'user@example.com',
password: 'securePassword123',
anonymousToken: anonymousResult.data?.session?.accessToken,
));
if (upgradeResult.error != null) {
print('Upgrade failed: ${upgradeResult.error!.message}');
return;
}
// Step 3: Verify verification code
final verifyResult = await upgradeResult.data!.verifyOtp!(
VerifyOtpParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Anonymous user upgrade successful');
}
signInWithPassword
Future<SignInRes> auth.signInWithPassword(SignInWithPasswordReq params)
Login with password. Supports login via username, email, or phone number.
Parameters
Response
Example
- Email Password Login
- Error Handling
- Username Password Login
- Phone Password Login
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}');
}
final result = await auth.signInWithPassword(
SignInWithPasswordReq(
email: 'user@example.com',
password: 'wrongPassword',
),
);
if (result.error != null) {
switch (result.error!.code) {
case 'invalid_credentials':
print('Incorrect username or password');
break;
case 'user_not_found':
print('User does not exist');
break;
default:
print('Login failed: ${result.error!.message}');
}
}
final result = await auth.signInWithPassword(
SignInWithPasswordReq(
username: 'myusername',
password: 'securePassword123',
),
);
if (result.isSuccess) {
print('Login successful: ${result.data?.user?.id}');
}
final result = await auth.signInWithPassword(
SignInWithPasswordReq(
phone: '13800138000',
password: 'securePassword123',
),
);
if (result.isSuccess) {
print('Login successful: ${result.data?.user?.id}');
}
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.isUseristrue, the existing user is signed in - If the user does not exist, a new account is registered and signed in
- Use
bindInfoto link a third-party identity during sign-in or sign-up
Parameters
Verification info, usually from the getVerification response
Verification code entered by the user
Username, email, or phone number
Login type: email or phone. Treated as email when set to email; otherwise treated as a phone number (automatically prefixed with +86)
Third-party identity binding info, e.g. {'providerToken': '...'} or {'providerId': '...'}
Response
Example
- Email OTP Login
- Phone OTP Login and Link Identity
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}');
}
final verification = await auth.getVerification(phoneNumber: '13800138000');
final result = await auth.signInWithUsername(
verificationInfo: VerificationInfo(
verificationId: verification.data!.verificationId,
isUser: verification.data!.isUser,
),
verificationCode: '123456',
username: '13800138000',
loginType: 'phone',
bindInfo: {'providerToken': 'pt-wechat'},
);
if (result.isSuccess) {
print('Login successful: ${result.data?.user?.id}');
}
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
shouldCreateUserparameter (default is true)
Parameters
Response
Example
- 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
Response
Example
- 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.
- The third-party provider must first be configured in CloudBase Platform / Authentication / Login Methods
tokenis required; ifprovideris omitted, generic token verification is used
Parameters
Response
Example
- 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
Async function to get custom login ticket
Response
Example
- Basic Usage
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
Example
- 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
Refresh token (optional, defaults to current session's refreshToken)
Response
Example
- 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
Response
Example
- 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
Logout configuration options (optional)
Response
Example
- 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
State change callback function
Response
Example
- 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
Example
- 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
Example
- 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
Example
- 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
Response
Example
- Update Basic Info
- Update Email (Requires Verification)
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}');
}
final result = await auth.updateUser(
UpdateUserReq(email: 'new@example.com'),
);
if (result.isSuccess && result.data?.verifyOtp != null) {
final verifyResult = await result.data!.verifyOtp!(
UpdateUserVerifyParams(token: '123456'),
);
if (verifyResult.isSuccess) {
print('Email updated successfully: ${verifyResult.data?.user?.id}');
}
}
deleteUser
Future<CloudBaseResponse<void>> auth.deleteUser(DeleteUserReq params)
Delete current user. Password is required for security verification.
Parameters
Response
Example
- 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
Example
- 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
Response
Example
- 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
Response
Example
- 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
Email or phone number
Redirect URL
Response
Example
- 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
Response
Example
- 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
Example
- 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 (one of email or phoneNumber)
Phone number (one of email or phoneNumber)
Response
Example
- 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
Verification ID
Verification code
Response
Example
- 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
OAuth callback params (optional; read from the URL when omitted)
Response
Example
- 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
Response
Example
- 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
Response
Example
- 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
Force a new CAPTCHA (default false)
State identifier
Response
CAPTCHA token, null on failure
Example
- Built-in Dialog
- Custom CAPTCHA Handler
// 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');
// Set a custom handler
app.captcha.onCaptchaRequired = (String captchaImageData) async {
// Show the CAPTCHA image and return the user input
final userInput = await showMyCustomCaptchaDialog(captchaImageData);
return userInput;
};
final token = await app.captcha.getCaptchaToken(state: 'register');
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
Original URL
State identifier
Force a new CAPTCHA. Default is false
Response
URL with captcha_token, or the original URL when no token is available
Example
- 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 identifier
Response
Example
- 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
CAPTCHA token
CAPTCHA entered by the user
Response
Example
- 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
No return value
Example
- Example
await app.captcha.clearCaptchaToken();
print('CAPTCHA token cleared');