DEV Community

陈杨
陈杨

Posted on

HarmonyOS5_Phone_Login_Tutorial_EN

✨ Hi, fellow HarmonyOS developers! Today, let's talk about how to integrate "Phone Number Login Authentication" into your application. Whether you're using "phone number + password" or "phone number + verification code," this step-by-step tutorial will guide you through it. Ready? Let's go~ 🚀


1. 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 encapsulated the core logic.

2. Environment Preparation

First, make sure your project has:

  1. Integrated the AGC Auth SDK.
  2. Enabled phone authentication capability 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

3. Core Function Implementation (with code)

🔑 Scenario 1: New User Registration

Two steps: Get verification code → Create account

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

auth.requestVerifyCode({
  action: VerifyCodeAction.REGISTER_LOGIN, // Shared type for registration and login
  lang: 'en_US', // SMS language
  sendInterval: 60, // SMS resend interval (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 (auto login)
auth.createUser({
  kind: 'phone',
  countryCode: '86',
  phoneNumber: '13812345678',
  password: 'Init@123', // Initial password (optional)
  verifyCode: '654321' // 6-digit verification 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' // User-set password
  }
}).then(user => {
  console.log("Login successful! Current user:", user);
}).catch(err => {
  if(err.code === 203817858) { // Special handling for wrong password
    console.warn("Wrong password, " + err.remainingTimes + " attempts remaining");
  }
});
Enter fullscreen mode Exit fullscreen mode

📲 Scenario 3: Verification Code Login

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

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

4. Account Management Tips

Update Linked Phone Number (Requires Login)

auth.getCurrentUser().then(user => {
  user.updatePhone({
    countryCode: '86',
    phoneNumber: '13887654321', // New number
    verifyCode: '112233',
    lang: "en_US"
  }).then(() => {
    console.log("Phone number updated successfully!");
  });
});
Enter fullscreen mode Exit fullscreen mode

Update Password (Post-Login Operation)

auth.getCurrentUser().then(user => {
  user.updatePassword({
    password: 'NewPwd@2024',
    providerType: 'phone' 
  });
});
Enter fullscreen mode Exit fullscreen mode

Forgot Password? One-click Reset!

// auth.requestVerifyCode({
//   action: VerifyCodeAction.RESET_PASSWORD,
//   // ...other parameters are the same as above
// });

// Execute reset
auth.resetPassword({
  kind: 'phone',
  password: 'FreshStart@123',
  phoneNumber: '13812345678',
  countryCode: '86',
  verifyCode: '665544'
});
Enter fullscreen mode Exit fullscreen mode

5. Pitfall Guide 🚧

  1. Sensitive Operation Protection: To change phone number/password, 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>.

6. Extended Capabilities 🔗

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

  • • Account Linking: Bind WeChat/Email for multi-platform login.
  • • 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 with ease! If you encounter any issues, feel free to ask in the comments. Don't forget to handle exceptions and logging in your actual development~

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

Top comments (0)