Integrating Auth Service into a Xamarin Android App - Huawei Developers

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?​

Related

How to quickly add Sign In with Email to your Android App

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 ?

Explore the world Trip Booking App- Part-1 login with Huawei ID

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201346103655580149&fid=0101188387844930001
Introduction
This article is based on Huawei Mobile Services application. I have developed Trip Booking Android app. We can provide the solution for HMS based multiple kits such as Account Kit, Huawei Ads, Huawei Map, and Huawei Analysts to use in Trip Booking. So users can book any trip.
In this application, users can plan trips and advance books. It will provide the ongoing trip cities wise with weather forecasting so that users can easily plan a trip and book trip and also can find popular cities with budget hotels and much more.
Service Process
{
"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"
}
The process is described as follows:
1. A user signs in to your app using a HUAWEI ID.
2. Your app sends a sign-in request to the Account SDK.
3. The Account SDK brings up the user sign-in authorization interface, explicitly notifying the user of the content to be authorized based on the authorization scope contained in the sign-in request.
4. After the user authorizes your app to access the requested content, the Account SDK returns the authorization code to your app.
5. Based on the authorization code, your app obtains the access token, refresh token, and ID token from the HUAWEI Account Kit server.
6. Based on the access token, your app server obtains openId of the user from the HUAWEI Account Kit server.
7. If the access token or ID token has expired, your app server obtains a new access token or ID token using the refresh token.
Prerequisite
1. A computer (desktop or laptop).
2. A Huawei phone used for running the app with HMS Core (APK) 3.0.0.300 or later.
3. A data cable used for connecting the computer to the Huawei phone.
4. Android Studio 3.0 or later.
5. Java SDK 1.7 or later.
6. HMS Core SDK 4.0.0.300 or later.
7. Must have Huawei Developer Account.
Things Need To Be Done
1. Create an app in AppGallery Connect and enable the service.
2. Create an Android Studio project.
3. Start development with kit integration inside the application.
4. Launch the application.
Create a project on AppGalleryConnect portal
1. Navigate to AppGalleryConnect, create a new project.
2. Enter all details regarding your application, enable Account Kit API, after that download the configuration JSON file, and then add into your android studio project.
Create a project in Android Studio:
Navigate to android studio and create a new android project, provide all details of your project, and then add AGC and Account kit SDK dependencies.
1. Add maven URL and add following AppGalleryConnect classpath.
Code:
buildscript {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.huawei.agconnect:agcp:1.0.0.300'
}
}
allprojects {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
2. Add the following dependencies in app module based Gradle file, then sync your project.
Code:
implementation "com.google.code.gson:gson:2.8.5"
implementation('com.huawei.hms:hwid:4.0.4.300')
implementation "com.squareup.okhttp3:okhttp:3.14.2"
implementation 'com.squareup.okio:okio:1.14.1'
Start development with kit integration inside the application
I have created the following package inside the project.
LoginActivity
In this screen, I have integrated login functionality with Huawei Id.
Which cover the following APIs
1. Call the HuaweiIdAuthParamsHelper.setAuthorizationCode API to send an authorization request.
Code:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setAuthorizationCode().createParams();
2. Call the getService API of HuaweiIdAuthManager to initialize the HuaweiIdAuthService object.
Code:
HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
3. Call the HuaweiIdAuthService.getSignInIntent method to bring up the HUAWEI ID sign-in authorization interface.
Code:
startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
4. Process the sign-in result after the authorization is complete.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, huaweiAccount.getDisplayName() + " signIn success ");
Log.i(TAG, "AccessToken: " + huaweiAccount.getAccessToken());
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("user", huaweiAccount.getDisplayName());
startActivity(intent);
this.finish();
} else {
Log.i(TAG, "signIn failed: " + ((ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN_CODE) {
//login success
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "signIn get code success.");
Log.i(TAG, "ServerAuthCode: " + huaweiAccount.getAuthorizationCode());
} else {
Log.i(TAG, "signIn get code failed: " + ((ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
}
MainActivity
In this screen, I have integrated all fragments which are related to application and also added Logout functionality.
Code:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getName();
private AppBarConfiguration mAppBarConfiguration;
private HuaweiIdAuthService mAuthManager;
private HuaweiIdAuthParams mAuthParam;
private void setUser(String name) {
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUsername = headerView.findViewById(R.id.txt_user_name);
navUsername.setText(name);
}
private void logOut() {
mAuthParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams();
mAuthManager = HuaweiIdAuthManager.getService(this, mAuthParam);
Task<Void> signOutTask = mAuthManager.signOut();
signOutTask.addOnSuccessListener(aVoid -> {
Log.i(TAG, "signOut Success");
Intent intent = new Intent(this, LoginScreen.class);
startActivity(intent);
this.finish();
})
.addOnFailureListener(e -> Log.i(TAG, "signOut fail"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
logOut();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Launch the application
Let us launch our application, see the result
If you have any doubts or queries. Leave your valuable comment in the comment section and do not forget to like and follow me.
References
https://developer.huawei.com/consumer/en/hms/huawei-accountkit
is it possible to sign in using phone number?
Very useful, thanks.

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.

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