How to quickly add Sign In with Email to your Android App - Huawei Developers

Certain kind of apps require user registration to provide relevant information or save user's generated content/preferences in a server. If you are building an app with this feature, you may be interested in Huawei Auth Service to quickly develop your Log In screen with support of the most popular Third-party accounts. I've talked about how to set up the Auth Service in a previous post, so now will show you how to add the Sign In with Email to your Huawei Auth Service implementation.
Previous requirements
A developer account
An app project on AGC with Auth Service integrated
Note: Auth service requires a Data Storage Location, be careful when selecting this, because your app will be only available to certain countries per location.
Enabling the service
You must enable the account types to be supported by Auth Service one by one. Enable the Email support by going to AGC > My projects > "Your Project" > Auth Service.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Auth Service configurtion panel
Layout
Add a button and an EditText to your Login screen to get the user's email.
Layout editor
Adding the logic
Add the onClickListener to your login button
Code:
mailBtn.setOnClickListener(this)
override fun onClick(v: View?) {
loadingDialog.show()
when (v?.id) {
R.id.hw -> signInWithHWID()
R.id.google_sign_in_button -> signInWithGoogle()
R.id.anon -> signInAnonymously()
R.id.mailBtn -> signInWithMail()
}
}
I suggest you using a regular expression to check if the given email has a proper format. If everything is ok, you can send a verification code to the email address
Code:
private fun signInWithMail() {
val input = mail.text.toString()
val regex = Regex("^[\\w-\\.][email protected]([\\w-]+\\.)+[\\w-]{2,4}\$")
if (!regex.matches(input)) {
Snackbar.make(mailBtn, "Please use a valid email", Snackbar.LENGTH_SHORT).show()
return
}
val settings = VerifyCodeSettings.newBuilder()
.action(ACTION_REGISTER_LOGIN) //ACTION_REGISTER_LOGIN/ACTION_RESET_PASSWORD
.sendInterval(30) // Minimum sending interval, ranging from 30s to 120s.
.build()
val task: Task<VerifyCodeResult> = EmailAuthProvider.requestVerifyCode(
input,
settings
)
task.addOnSuccessListener {
//The verification code application is successful.
Snackbar.make(
mailBtn,
"Verification code sent to your mailbox",
Snackbar.LENGTH_SHORT
).show()
Log.e("EmailAuth", "success")
//Display dialog
val dialog = VerifyDialog(this, input)
dialog.listener = this
dialog.show()
}
.addOnFailureListener {
Log.e("EmailAuth", it.toString())
}
}
In my case, I've chosen to show a dialog, waiting for the verification code.
Dialog layout
Then the dialog will report the given code and password to the Fragment / Activity
Code:
class VerifyDialog(val context: Context,val email: String):DialogInterface.OnClickListener{
lateinit var view:View
var listener:VerificationListener?=null
var alertDialog: AlertDialog
init{
val inflater=LayoutInflater.from(context)
view=inflater.inflate(R.layout.dialog_verify,null)
val builder=AlertDialog.Builder(context)
builder.setTitle("Email Verification")
.setView(view)
.setPositiveButton("ok",this)
.setNegativeButton("Cancel",this)
.setCancelable(false)
alertDialog=builder.create()
}
public fun show(){
alertDialog.show()
}
override fun onClick(dialog: DialogInterface?, which: Int) {
when(which){
DialogInterface.BUTTON_POSITIVE ->{
val code=view.inputCode.text.toString()
if(code==""){
Snackbar.make(view,"Please input the code",Snackbar.LENGTH_SHORT).show()
return
}
val pass=view.inputPass.text.toString()
val vPass=view.confirmPass.text.toString()
if(pass.isEmpty()||pass!=vPass){
Snackbar.make(view,"Passwords doesn't match",Snackbar.LENGTH_SHORT).show()
return
}
listener?.onVerification(code,email,pass)
}
DialogInterface.BUTTON_NEGATIVE ->{
dialog?.dismiss()
listener?.onCancel()
}
}
}
public interface VerificationListener{
fun onVerification(code:String,email:String,password:String)
fun onCancel()
}
}
Report the code and password to AGC, so the user can use the password to sign in the next time.
Note: Setting the password is not mandatory.
Code:
override fun onVerification(code: String, email: String, password: String) {
val emailUser = EmailUser.Builder()
.setEmail(email)
.setVerifyCode(code)
.setPassword(password) // Optional. If this parameter is set, the current user has created a password and can use the password to sign in.
// If this parameter is not set, the user can only sign in using a verification code.
.build()
AGConnectAuth.getInstance().createUser(emailUser)
.addOnSuccessListener {
// After an account is created, the user is signed in by default.
startNavDrawer(it.user)
}
.addOnFailureListener {
Log.e("AuthSevice","Email Sign In failed $it")
}
}
Conclusion
Now your users can Sign In with their email adress. You can check the full example here: DummyApp
Reference
Official document:https://developer.huawei.com/consum...-connect-Guides/agc-auth-service-introduction

Hi am trying to implement email login but am getting email null do we need to anything.

Hi Is there any ways to use Huawei Auth Service as one like firebase UI ?

Related

How to add or delete record to/from table in Huawei Cloud DB ?

Hello everyone, in this story, I will try to show you basic usage of HMS Cloud Db executeUpsert() and executeDelete() functions.
First, please be sure that having a project on cloud db up and running. If it is your first Cloud Db project and don’t know what to do, feel free to visit here.
For our scenario, we will have two tables named BookmarkStatus and LikeStatus. BookmarkStatus and LikeStatus tables holds a record for each user’s bookmark/like for the specified object and deletes the record when user remove his/her like or bookmark.
Let’s start with initializing our cloud db object. I will initialize cloud db object once when application started (in SplashScreen) and use it through the application.
Note : Make sure you have initialized your cloud db object before any of your cloud db operations.
Click to expand...
Click to collapse
Code:
companion object {
fun initDb() {
AGConnectCloudDB.initialize(ContextProvider.getApplicationContext())
}
}
fun dbGetInstance(){
mCloudDb = AGConnectCloudDB.getInstance()
}
Then, create a base viewModel to call certain functions of cloud db instead of calling them in every viewModel.
Code:
open class BaseViewModel : ViewModel() {
var mCloudDbZoneWrapper: CloudDbRepository =
CloudDbRepository()
init {
mCloudDbZoneWrapper.createObjectType()
mCloudDbZoneWrapper.openCloudDbZone()
}
}
Here is what createObjectType() and openCloudDbZone() functions do.
Code:
/*
Create object type
*/
fun createObjectType() {
dbGetInstance()
try {
mCloudDb!!.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo())
} catch (exception: AGConnectCloudDBException) {
Log.w("CloudDbRepository", exception.errMsg)
}
}
/*
Following method opens cloud db zone with given configs.
*/
fun openCloudDbZone() {
val mConfig: CloudDBZoneConfig = CloudDBZoneConfig(
"YOUR_CLOUD_DB_NAME", CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC
)
mConfig.persistenceEnabled = true
try {
mCloudDbZone = mCloudDb!!.openCloudDBZone(mConfig, true)
} catch (exception: AGConnectCloudDBException) {
Log.w("CloudDbRepository", exception.errMsg)
}
}
Now we have all settings done. All we need to do is calling executeUpsert() and executeDelete() functions properly in related repositories.
Note: Please make sure that all needed permissions are granted to add or delete to/from table.
Click to expand...
Click to collapse
Code:
private fun bookmarkResult(
snapshot: CloudDBZoneSnapshot<BookmarkStatus>,
bookmark: BookmarkStatus,
triggered: Boolean
) {
val bookmarkStatsCursor: CloudDBZoneObjectList<BookmarkStatus> = snapshot.snapshotObjects
try {
if (bookmarkStatsCursor.hasNext()) {
val bookmarkStats = bookmarkStatsCursor.next()
if (bookmarkStats != null && bookmarkStats.object != null) {
if (triggered) {
//deleteBookmark
val deleteTask = mCloudDBZone.executeDelete(bookmarkStats)
deleteTask.addOnSuccessListener {
Log.w(TAG, "BookmarkDelete success")
bookmarkStatus.postValue(false)
}.addOnFailureListener {
Log.w(TAG, "BookmarkDelete fail" + it.message)
}
} else {
bookmarkStatus.postValue(true)
}
}
} else {
if (triggered) {
//add bookmark
val upsertTask = mCloudDBZone.executeUpsert(bookmark)
upsertTask.addOnSuccessListener {
Log.w(TAG, "BookmarkAdd success")
bookmarkStatus.postValue(true)
}.addOnFailureListener {
Log.w(TAG, "BookmarkDelete fail" + it.message)
}
} else {
bookmarkStatus.postValue(false)
}
}
} catch (exception: Exception) {
}
snapshot.release()
}
In this function, triggered parameter is for if user clicked bookmark button or not if clicked then value is true.
Here is the logic;
If user bookmarked the given object (which is queried in another method and passed as a parameter to this method as snapshot) then bookmarkStatsCursor.hasNext() returns true and if not triggered , this means user bookmarked the object and is trying to display bookmark status and all we need to do is using postValue() of the observable property bookmarkStatus and pass the value as true. Let’s say user has a record on BookmarkStatus table and triggered is true then we can say user is trying to remove bookmark of the object. So we need to use executeDelete(bookmark) to delete bookmark from table. With the help of addOnSuccessListener we will post value as false which means user does not have a bookmark on the given object anymore.
If user does not have a bookmark in given object and triggered is false, this means user did not bookmark object and trying to display bookmark status. We will post value as false. If triggered is true then, user is trying to add bookmark to that object. In this situation, we will add a record to the bookmark table using executeUpsert(bookmark) method.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Note that you can use addOnFailureListener to catch errors occurred during adding or deleting functions.
To add or delete records to/from LikeStatus table, you can use same logic with BookmarkStatus table given above.
So, as you can see, it is very simple to implement cloud db in your project and you can apply all CRUD functions simply as demonstrated above
References
https://developer.huawei.com/consum...llery-connect-Guides/agc-clouddb-introduction

Implementing SMS Verification with Huawei SMS Retriever

Hi everyone! Today I will briefly walkthrough you about how to implement an SMS Retriever system using Huawei’s SMSRetriever service.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
First of all, let’s start with why do we need this service in our apps. Applications that involve user verification usually do this with an SMS code, and this SMS code is entered to a field in the app to verify user account. These sms codes are named as One-Time-Password, OTP for short. OTP’s can be used for verification of real user or increasing account security. Our purpose here is to retrieve this code and automatically enter it to the necessary field in our app. So let’s begin!
Our steps through the guide will be as:
Complete HMS Service implementation
1 — Require SMS read permission
2 — Initiate ReadSmsManager
3 — Register broadcast receiver for SMS
4 — Send SMS for user
5 — Register broadcast receiver for OTP — to extract code from SMS —
6 — Create SMSBroadcastReceiver class
1 — We begin by adding our required permission to the AndroidManifest.xml
XML:
<uses-permission android:name="android.permission.SEND_SMS" />
Note: Don’t forget to check if user has given permission.
Code:
val permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
if (permissionCheck == PackageManager.PERMISSION_GRANTED)
// Send sms
else
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.SEND_SMS), SEND_SMS_REQUEST_CODE)
2 — Then we add the ReadSmsManager to initiate our SMS service.
Before ReadSmsManager code snippet, we have to add Huawei Account Kit implementation.
Code:
implementation 'com.huawei.hms:hwid:5.1.0.301'
After Gradle sync, we can add the SMS manager to our class.
Code:
val task = ReadSmsManager.startConsent([email protected], mobileNumber)
task.addOnCompleteListener {
if (task.isSuccessful) {
Toast.makeText(this, "Verification code sent successfully", Toast.LENGTH_LONG).show()
} else
Toast.makeText(this, "Task failed.", Toast.LENGTH_LONG).show()
}
3 — For SMS broadcast receiver, we need to add this little code block.
Code:
val intentFilter = IntentFilter(READ_SMS_BROADCAST_ACTION)
registerReceiver(SmsBroadcastReceiver(), intentFilter)
Note: After you add this code block, you will get an error saying SmsBroadcastReceiver cannot be found, because we didn’t define it yet. We are just getting our SmsActivity ready. We will be adding it once we are done here.
4 — After we register our receiver, we can send the SMS to our user.
Code:
val smsManager = SmsManager.getDefault()
smsManager.sendTextMessage(
mobileNumber,
null,
"Your verification code is $otp",
null,
null
)
Note: here otp will cause an error as it is not defined anywhere yet. You should implement a random OTP generator fitting your likings and assign the value to otp .
5 — Now that we sent an SMS to user, we should register the broadcast receiver to be able to retrieve the code from it.
Code:
val filter = IntentFilter()
filter.addAction("service.to.activity.transfer")
val otpReceiver = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
intent.getStringExtra("sms")?.let { data ->
// You should find your otp code here in `data`
}
}
}
registerReceiver(otpReceiver, filter)
Note: Once we complete our classes, you should be setting your otp value to your view. This part is left out in the code snippet as view bindings and data bindings may vary on projects.
6 —Finally, where we get to read the messages and find our code.
Code:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.huawei.hms.common.api.CommonStatusCodes
import com.huawei.hms.support.api.client.Status
import com.huawei.hms.support.sms.common.ReadSmsConstant
class SmsBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val bundle = intent!!.extras
if (bundle != null) {
val status: Status? = bundle.getParcelable(ReadSmsConstant.EXTRA_STATUS)
if (status?.statusCode == CommonStatusCodes.TIMEOUT) {
// Process system timeout
} else if (status?.statusCode == CommonStatusCodes.SUCCESS) {
if (bundle.containsKey(ReadSmsConstant.EXTRA_SMS_MESSAGE)) {
bundle.getString(ReadSmsConstant.EXTRA_SMS_MESSAGE)?.let {
val local = Intent()
local.action = "service.to.activity.transfer"
local.putExtra("sms", it)
context!!.sendBroadcast(local)
}
}
}
}
}
}
So that’s it. You should be able to successfully register for SMS sending and retrieving, then read OTP from content and use in whatever way you like.
Thanks for reading through the guide and I hope it is simple and useful for you. Let me know if you have any suggestions or problems.
References
https://developer.huawei.com/consum...upport-sms-readsmsmanager-0000001050050553-V5
https://developer.huawei.com/consum...Guides/authotize-to-read-sms-0000001061481826
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98

How Can I Quickly Integrate AppGallery Connect Auth Service into a Web App?

Currently, AppGallery Connect Auth Service also supports web apps. I have integrated the service by referring to the official documentation. You can also download the sample code for reference. I’ll show you the simple procedure in this post.
Integration Procedure​1.Enabling the Service
a) Create a web app in AppGallery Connect.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
b) Enable Auth Service.
c) Enable the Anonymous account, Mobile number, and Email address authentication modes.
2. Integrating the AppGallery Connect SDK
a) Add the configuration code to the login.vue file.
b) In Huawei Quick App IDE, open your quick app project, integrate the AppGallery Connect JavaScript SDK to your project, and import the module for Auth Service.
3. Implementing Functions
a) For anonymous accounts:
Add a button for anonymous sign-in to your test app and click the button. The sample code is as follows:
JavaScript:
loginAnonymously() {
console.log("JS-SDK login anonymously!");
agconnect.auth().signInAnonymously().then(user => {
// Sign-in successful.
alert("loginAnonymously successfully");
this.getUserInfo();
}).catch(error => {
// Sign-in error.
alert(error)
});
},
When the anonymous sign-in is successful, a UID is displayed.
b) For mobile phone numbers or email addresses (password mode):
Add a text box for users to input the mobile phone number or email address and a text box for the password input to your test app. Input required information to sign in to the app. The sample code is as follows:
JavaScript:
loginByPwd() {
console.log("JS-SDK auth(): login...")
let credential = null;
if (this.dataForm_sdk.password == '') {
alert("Please typein password!");
return;
}
switch (this.provider) {
case 'phone':
credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword('86', this.dataForm_sdk.account, this.dataForm_sdk.password);
break;
case 'email':
credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(this.dataForm_sdk.account, this.dataForm_sdk.password);
break;
default:
break;
}
if (credential == null) {
console.log("credential null!");
return;
}
agconnect.auth().signIn(credential).then(res => {
alert("Sign-in successful.");
this.getUserInfo();
}).catch(err => {
alert(err);
});
},
c) For mobile phone numbers or email addresses (verification code mode):
Add a text box for users to input the mobile phone number or email address and a button for obtaining a verification code to your test app. Input required information and click the button to obtain the verification code. The sample code is as follows:
JavaScript:
getVerifyCode() {
console.log("request for email verifycode...")
this.dataForm_sdk.verifyCode = '';
switch (this.provider) {
case 'phone':
// Obtain a verification code.
agconnect.auth.PhoneAuthProvider.requestVerifyCode('86', this.dataForm_sdk.account,agconnect.auth.Action.ACTION_REGISTER_LOGIN, 'zh_CN', 90).then(ret => {
alert("Request sent.");
}).catch(error => {
alert("Request failed.");
});
break;
case 'email':
agconnect.auth.EmailAuthProvider.requestVerifyCode(this.dataForm_sdk.account, agconnect.auth.Action.ACTION_REGISTER_LOGIN, 'zh_CN', 120).then(ret => {
// Request sent.
alert("Request successful.");
}).catch(error => {
// Request failed.
alert(error)
});
break;
default:
break;
}
},
Add a button for sign-in using a verification code. The sample code is as follows:
JavaScript:
loginByVerifyCode() {
if (this.dataForm_sdk.verifyCode == '') {
alert("Enter the verification code.");
return;
}
let credential = null;
switch (this.provider) {
case 'phone':
credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode('86', this.dataForm_sdk.account, this.dataForm_sdk.password, this.dataForm_sdk.verifyCode);
break;
case 'email':
credential = agconnect.auth.EmailAuthProvider.credentialWithVerifyCode(this.dataForm_sdk.account, this.dataForm_sdk.password, this.dataForm_sdk.verifyCode);
break;
case 'QQ':
break;
case 'weChat':
break;
default:
break;
}
if (credential == null) {
console.log("credential null!")
return;
}
agconnect.auth().signIn(credential).then(res => {
alert("Sign-in successful.");
this.getUserInfo();
}).catch(err => {
alert(err);
});
},
Summary
AppGallery Connect Auth Service provides quite a lot of authentication modes and the integration is simple to complete.
If you have any other questions, please check the official demo.

Integrating Auth Service into a Xamarin Android App

Xamarin (Microsoft) is a multi-system development platform for mobile services that many developers use. Many AppGallery Connect services now support Xamarin, including Auth Service. Here I’ll explain on how to integrate Auth Service into your Xamarin.Android app that requires mobile number sign-in support.
Install the Xamarin environment.​You’ll need to first download and install Visual Studio 2019.
Open Visual Studio and select Mobile development with .NET to install the Xamarin environment.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Next make sure you have enabled the Auth Service in AppGallery Connect.
Open Visual Studio, click Create a new project in the start window, select Mobile App (Xamarin.Forms), and set the app name and other required information.
Right-click your project and choose Manage NuGet Packages.
Search for the Huawei.Agconnect.Auth package on the displayed page and install it.
Download the JSON service file from your AppGallery project and add it into the *Assets directory in your project.
Create a new class named HmsLazyInputStreams.cs, and implement the following code to read the JSON file.
Code:
using System;
using System.IO;
using Android.Util;
using Android.Content;
using Huawei.Agconnect.Config;
namespace XamarinAuthDemo
{
class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context) : base(context)
{
Get(context);
}
public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error(e.ToString(), "Failed to get input stream" + e.Message");
return null;
}
}
}
}
Then add the following code to AttachBaseContext under MainActivity.
Code:
protected override void AttachBaseContext(Context context){
base.AttachBaseContext(context);
AGConnectServicesConfig config = AGConnectServicesConfig.FromContext(context);
config.OverlayWith(new HmsLazyInputStream(context));
}
Right-click your project and choose Properties. Click Android Manifest on the displayed page, and set a package name.
Once you’ve completed all of these preparations, you’ll be able to develop app functions.
If your app requires mobile number sign-in support, the Auth Service SDK can help you implement both sign-up and sign-in for this authentication mode. You’ll need to send verification codes to your users for both stages. Auth Service can help you with that as well.
Setup Mobile Number verification​Create a VerifyCodeSettings object that contains the SMS messaging settings, including the action and language.
Code:
VerifyCodeSettings settings = VerifyCodeSettings.NewBuilder()
.Action(VerifyCodeSettings.ActionRegisterLogin)
.SendInterval(30)
.Locale(Locale.English)
.Build();
Call the RequestVerifyCodeAsync method to send a request to the Auth Service server, and pass the country code and mobile number entered by a user, and the VerifyCodeSettings object you just created, for Auth Service to send a verification code SMS message to the user.
Code:
string countryCode = edtCountryCode.Text.ToString().Trim();
string phoneNumber = edtAccount.Text.ToString().Trim();
try {
var requestVerifyCode = AGConnectAuth.Instance.RequestVerifyCodeAsync(countryCode, phoneNumber, settings);
VerifyCodeResult verifyCodeResult = await requestVerifyCode;
if(requestVerifyCode.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) {
Toast.MakeText(this, "The verification code is sent successfully! ", ToastLength.Short).Show();
}
} catch (Exception ex) {
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
Upon receiving the verification code, the user can start sign-up.
First, you’ll need to create a PhoneUser object to store the user’s inputs, including the mobile number, country code, verification code, and password. The user can choose whether to set a password. If so, they’ll need to enter a password when signing in to your app.
Code:
string countryCode = edtCountryCode.Text.ToString().Trim();
string phoneNumber = edtAccount.Text.ToString().Trim();
string password = edtPassword.Text.ToString().Trim();
string verifyCode = edtVerifyCode.Text.ToString().Trim();
// Create a PhoneUser object.
PhoneUser phoneUser = new PhoneUser.Builder()
.SetCountryCode(countryCode)
.SetPhoneNumber(phoneNumber)
.SetPassword(password)
.SetVerifyCode(verifyCode)
.Build();
Call the CreateUserAsync method to create a user.
Code:
try {
// Create a mobile number user.
var phoneUserResult = AGConnectAuth.Instance.CreateUserAsync(phoneUser);
ISignInResult signInResult = await phoneUserResult;
if (phoneUserResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) {
// After the user is created, they are automatically signed in to your app.
StartActivity(new Intent(this, typeof(MainActivity)));
}
} catch (Exception ex) {
Toast.MakeText(this, "Create User Fail:" + ex.Message, ToastLength.Long).Show();
}
Once sign-up is complete, the Auth Service SDK will automatically sign the user in to your app, and you won’t need to call the sign-in API again.
For an existing user, you need to implement the sign-in process, either via a verification code or a password.
Code:
string countryCode = edtCountryCode.Text.ToString().Trim();
string phoneNumber = edtAccount.Text.ToString().Trim();
string password = edtPassword.Text.ToString().Trim();
string verifyCode = edtVerifyCode.Text.ToString().Trim();
IAGConnectAuthCredential credential;
if (TextUtils.IsEmpty(verifyCode)) {
credential = PhoneAuthProvider.CredentialWithPassword(countryCode, phoneNumber, password);
} else {
credential = PhoneAuthProvider.CredentialWithVerifyCode(countryCode, phoneNumber, password, verifyCode);
}
try {
AGConnectAuth connectAuth = AGConnectAuth.Instance;
var signInResult = AGConnectAuth.Instance.SignInAsync(credential);
ISignInResult result = await signInResult;
if (signInResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)) {
Log.Debug(TAG, signInResult.Result.ToString());
StartActivity(new Intent(this, typeof(MainActivity)));
Finish();
}
} catch (Exception ex) {
Log.Error(TAG, ex.Message);
Toast.MakeText(this, "SignIn failed: " + ex.Message, ToastLength.Long).Show();
}
You can call CredentialwithPassword or CredentialWithVerifyCode to generate a credential for a password sign-in or a verification code sign-in, respectively. Then call the SignInAsync method to pass the credential for sign-in.
And thats it! We now have a fully functional authentication system using the users mobile number to confirm they are who they say they are.
Xamarin is a free tool or paid?​

Implement Huawei AppGallery Auth Service in your Xamarin Android app with Facebook Login support

Xamarin (Microsoft) is a multi-system development platform for mobile services that many developers use. Many AppGallery Connect services now support Xamarin, including Auth Service. Here I’ll explain on how to integrate Auth Service into your Xamarin.Android app and use the 3rd party auth support for Facebook.
Install the Xamarin environment and project setup.​You’ll need to first download and install Visual Studio 2019.
Open Visual Studio and select Mobile development with .NET to install the Xamarin environment.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Next make sure you have enabled the Auth Service in AppGallery Connect.
Open Visual Studio, click Create a new project in the start window, select Mobile App (Xamarin.Forms), and set the app name and other required information.
Right-click your project and choose Manage NuGet Packages.
Search for the Huawei.Agconnect.Auth package on the displayed page and install it.
Download the JSON service file from your AppGallery project and add it into the *Assets directory in your project.
Create a new class named HmsLazyInputStreams.cs, and implement the following code to read the JSON file.
Code:
using System;
using System.IO;
using Android.Content;
using Android.Util;
using Huawei.Agconnect.Config;
namespace AppLinking1
{
public class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context)
: base(context)
{
}
public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error("Hms", $"Failed to get input stream" + e.Message);
return null;
}
}
}
}
Right-click your project and choose Properties. Click Android Manifest on the displayed page and set a package name
Follow the process that Facebook describes to setup your application with their platform. Details can be found here
Finally the last thing we need to do is install the Xamarin Facebook login package.
Right-click your project and choose Manage NuGet Packages. Search for Xamarin.Facebook.Login.Android and install it.
Implement Facebook Auth​Create a login button within your application, this will use the below code to start the login process getting the specific requested account details from Facebook and process this using the call back.
Code:
private void ImgFacebook_Click(object sender, EventArgs e){
callBackManager = CallbackManagerFactory.Create();
ICollection<string> collection = new List<string>();
collection.Add("public_profile");
collection.Add("user_friends");
LoginManager.Instance.LogInWithReadPermissions(this, collection);
LoginManager.Instance.RegisterCallback(callBackManager, new FacebookCallback(this));
}
The Facebook Callback then looks like:
Code:
private class FacebookCallback : Java.Lang.Object, IFacebookCallback {
LoginActivity loginActivity;
public FacebookCallback(LoginActivity loginActivity) {
this.loginActivity = loginActivity;
}
public void OnCancel() {
Log.Debug("IFacebookCallback", "Cancelled.");
}
public void OnError(FacebookException error) {
Log.Error("IFacebookCallback", "Failed: " + error.Message);
}
public void OnSuccess(Java.Lang.Object result) {
LoginResult loginResult = (LoginResult)result;
Log.Debug("IFacebookCallback", "Facebook login successfuly. Access token: " + loginResult.AccessToken.Token);
IAGConnectAuthCredential credential = FacebookAuthProvider.CredentialWithToken(loginResult.AccessToken.Token);
try {
AGConnectAuth connectAuth = AGConnectAuth.Instance;
var signInResult = AGConnectAuth.Instance.SignInAsync(credential);
ISignInResult result = await signInResult;
if (signInResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)){
Log.Debug(TAG, signInResult.Result.ToString());
StartActivity(new Intent(this, typeof(MainActivity)));
Finish();
}
} catch (Exception ex) {
Log.Error(TAG, ex.Message);
Toast.MakeText(this, "SignIn failed: " + ex.Message, ToastLength.Long).Show();
}
}
}
In the OnSuccess method, we have obtained the access token and generated a credential for Facebook Login, and called SignInAsync to pass the credential for sign-in.
Finally, forward OnActivityResult to the callBackManager.
Code:
if (requestCode == 64206){
callBackManager.OnActivityResult(requestCode, (int)resultCode, data);
}
The result code 64206 is defined by Facebook in its Login SDK. It is used to identify the callback for Facebook Login when there are multiple callbacks in OnActivityResult. An interesting fact is that, the hexadecimal value of 64206 is 0xFACE, which is a little trick from Facebook.

Categories

Resources