DEV Community

陈杨
陈杨

Posted on

HarmonyOS5-Cloud-Service-Phone-Login-Tutorial

I. Why Choose Phone Number Authentication?

Before we dive into the code, let's talk about its advantages:

  • User-Friendly: No need to remember complex usernames.
  • High Security: Dual verification mechanism (SMS + password).
  • Quick Integration: The HarmonyOS Auth SDK has already encapsulated the core logic.

II. Environment Setup

First, make sure your project has:

  1. Integrated the AGC Auth SDK.
  2. Enabled phone authentication in the AGC console.
  3. Added permissions in <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">module.json5</font>:
"requestPermissions": [
  {"name": "ohos.permission.READ_SMS"} // If you need to automatically read the SMS verification code
]
Enter fullscreen mode Exit fullscreen mode

III. Core Feature Implementation (with Code)

🔑 Scenario 1: New User Registration

A two-step process: Get verification code → Create account

// Step 1: Request verification code
import auth, { VerifyCodeAction } from '@hw-agconnect/auth';

auth.requestVerifyCode({
  action: VerifyCodeAction.REGISTER_LOGIN, // Action type for registration/login
  lang: 'en_US',                           // Language of the SMS message
  sendInterval: 60,                        // Resend interval in seconds
  verifyCodeType: {
    phoneNumber: '13812345678',            // Remember to replace with a real number!
    countryCode: "86",
    kind: "phone"
  }
}).then(() => {
  console.log("Verification code sent. Please check your messages~");
}).catch(err => {
  console.error("Failed to send:", err.message);
});

// Step 2: Create user (and sign in automatically)
auth.createUser({
  kind: 'phone',
  countryCode: '86',
  phoneNumber: '13812345678',
  password: 'Init@123', // Initial password (optional)
  verifyCode: '654321'  // The 6-digit code received by the user
}).then(user => {
  console.log("Registration successful! UID:", user.uid);
});
Enter fullscreen mode Exit fullscreen mode

🔐 Scenario 2: Password Login

auth.signIn({
  credentialInfo: {
    kind: 'phone',
    phoneNumber: '13812345678',
    countryCode: '86',
    password: 'your_password' // The password set by the user
  }
}).then(user => {
  console.log("Login successful! Current user:", user);
}).catch(err => {
  if(err.code === 203817858) { // Special handling for incorrect password
    console.warn("Incorrect password. Remaining attempts:", err.remainingTimes);
  }
});
Enter fullscreen mode Exit fullscreen mode

📲 Scenario 3: Verification Code Login

// First, request the code (same as registration)
// auth.requestVerifyCode({
//   action: VerifyCodeAction.REGISTER_LOGIN,
//   // ...other parameters are the same as above
// });

// Then, sign in with the verification code
auth.signIn({
  credentialInfo: {
    kind: 'phone',
    phoneNumber: '13812345678',
    countryCode: '86',
    verifyCode: '123456' // The verification code from SMS
  }
}).then(user => {
  console.log("Passwordless login successful!");
});
Enter fullscreen mode Exit fullscreen mode

IV. Account Management Tips

Update Linked Phone Number (Requires Login)

// First, get the current user
// auth.getCurrentUser().then(user => {
  // Then, update the phone number
  user.updatePhone({
    countryCode: '86',
    phoneNumber: '13887654321', // New phone number
    verifyCode: '112233',      // Verification code for the new number
    lang: "en_US"
  }).then(() => {
    console.log("Phone number updated successfully!");
  });
// });
Enter fullscreen mode Exit fullscreen mode

Change Password (After Login)

// First, get the current user
// auth.getCurrentUser().then(user => {
  // Then, update the password
  user.updatePassword({
    password: 'NewPwd@2024',
    providerType: 'phone'
  });
// });
Enter fullscreen mode Exit fullscreen mode

Forgot Password? Reset it!

// Step 1: Request a password reset verification code
// auth.requestVerifyCode({
//   action: VerifyCodeAction.RESET_PASSWORD,
//   // ...other parameters are the same as above
// });

// Step 2: Perform the reset
auth.resetPassword({
  kind: 'phone',
  password: 'FreshStart@123', // The new password
  phoneNumber: '13812345678',
  countryCode: '86',
  verifyCode: '665544' // The verification code for password reset
});
Enter fullscreen mode Exit fullscreen mode

V. Pitfall Guide 🚧

  1. Sensitive Operation Protection: To change phone number/password, the user must have logged in within the last 5 minutes.
  2. Error Code Handling:
    • <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">203817932</font>: Verification code error.
    • <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">203817933</font>: Verification code expired.
    • <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">203817945</font>: Operation too frequent.
  3. Multi-Device Login: Enable support via <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">auth.settings.enableMultiDevice(true)</font>.

VI. Extended Capabilities 🔗

Want to make your authentication system even more powerful? Try these:

  • • Account Linking: Bind WeChat/Email for multiple login methods.
  • • Cloud Function Triggers: Listen for user registration/login events.
  • • Security Reinforcement: Enable Two-Factor Authentication (2FA).

Final Words

Hope this guide helps you master HarmonyOS phone authentication! If you encounter any issues, feel free to ask and discuss in the comments section. Don't forget to implement proper error handling and logging in your actual development~

If there are other features you'd like to learn about, let me know in the comments! See you next time~ 👋 (End of article)

Top comments (0)