Integrating Huawei’s AppGallery Connect Auth Service for iOS - Huawei Developers

Auth Service helps you quickly and easily develop account registration and sign-in functions for your app.
This service is offered completely free of charge and supports a range of platforms including Android and iOS!
Today we are going to take a look at how this can be quickly integrated into an iOS application.
Enabling Auth Service​To enable Auth Service, sign in to AppGallery Connect, click My projects, click your project card, and select an app for SDK integration from the app drop-down list at the top of the page. Then go to Build > Auth Service, and enable the service if you haven’t already.
{
"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"
}
Integrating the Service SDK​If you are using Xcode, you need to integrate the service SDK into your Xcode project using CocoaPods.
Add the AppGallery Connect configuration file of the app to your Xcode project.
Sign in to AppGallery Connect and click My projects.
Click your project card and select an app for SDK integration from the app drop-down list at the top of the page.
Go to Project settings > General information and download agconnect-services.plist under App information.
Copy the agconnect-services.plist file to your app’s module directory.
Create a PodFile​Open the CLI and navigate to the Xcode project. Then, create a Podfile. Skip this step if a Podfile already exists.
cd project-directory
pod init
Edit the PodFile​Integrate the service SDK.
Add the pod dependency AGConnectAuth to the Podfile.
target 'AGConnectAuthDemo' do
pod 'AGConnectAuth'
end
Install the pod and open the .xcworkspace file to view the project.
pod install
Designing the UI​You can create a layout page in the Xcode project and design the UI based on the following figure, to allow users to register an account on your app using a mobile number or email address.
Enabling Required Authentication Modes​
Sign in to AppGallery Connect and click My projects.
Click your project card and select an app from the app drop-down list at the top of the page.
Go to Build > Auth Service. On the Authentication mode tab page, enable Mobile number and Email address in the Operation column.
Developing Functions​Associate Storyboard with ViewController so that you can obtain parameters required for sign-up and sign-in through text boxes
Swift:
@IBOutlet weak var phoneText: UITextField!// Text box for entering a mobile number.
@IBOutlet weak var phoneVertifyText: UITextField!// Text box for entering a verification code sent to the mobile number.
@IBOutlet weak var phonePassword: UITextField!// Text box for entering the account password.
@IBOutlet weak var emailText: UITextField!// Text box for entering an email address.
@IBOutlet weak var emailVertifyText: UITextField!// Text box for entering a verification code sent to the email address.
@IBOutlet weak var emailPassword: UITextField!// Text box for entering the account password.
Mobile Number​If the mobile number entered has not been used to register an account, you need to send a verification code to it to check whether it belongs to the user. Enter a mobile number and tap Send verification code. Then call the method for requesting a verification code and obtain the result in the callback.
Swift:
@IBAction func phoneSendVertifyCode(_ sender: Any) {
let setting = AGCVerifyCodeSettings.init(action: AGCVerifyCodeAction.registerLogin, locale: nil, sendInterval: 30)
AGCPhoneAuthProvider.requestVerifyCode(withCountryCode: "86", phoneNumber: phoneText.text ?? "", settings: setting).onSuccess { (results) in
// A verification code is successfully sent to the mobile number.
}.onFailure { (error) in
// No verification code is sent to the mobile number.
}
}
Enter the verification code you received and the password set for your account. Tap the register button, call the method for mobile number registration, and obtain the result in the block callback.
Swift:
@IBAction func register(_ sender: Any) {
AGCAuth.instance().createUser(withCountryCode: "86", phoneNumber: phoneText.text ?? "", password: phonePassword.text ?? "", verifyCode: phoneVertifyText.text ?? "").onSuccess { (result) in
// The mobile number is successfully registered.
}.onFailure { (error) in
// The mobile number fails to be used for sign-up.
}
}
After successfully registering an account, enter the mobile number and password you set, and tap login to sign in to your app. Congratulations, you have now successfully enabled registration and sign-in with a mobile number for your app.
Swift:
@IBAction func login(_ sender: Any) {
let credential = AGCPhoneAuthProvider.credential(withCountryCode: "86", phoneNumber: phoneText.text ?? "", password: phonePassword.text ?? "")
AGCAuth.instance().signIn(credential: credential).onSuccess { (result) in
// Sign-in success.
}.onFailure { (error) in
// Sign-in failed.
}
}
Email​If the email address entered has not been used to register an account, you need to send a verification code to it. Enter the email address and tap Send verification code. Then call the method for requesting a verification code and obtain the result in the callback.
Swift:
@IBAction func emailSendVertifyCode(_ sender: Any) {
let setting = AGCVerifyCodeSettings.init(action: AGCVerifyCodeAction.registerLogin, locale: nil, sendInterval: 30)
AGCEmailAuthProvider.requestVerifyCode(withEmail: emailText.text ?? "", settings: setting).onSuccess { (result) in
// A verification code is successfully sent to the email address.
}.onFailure { (error) in
// No verification code is sent to the email address.
}
}
Enter the verification code you received and the sign-in password, and tap register.
Swift:
@IBAction func register(_ sender: Any) {
AGCAuth.instance().createUser(withEmail: emailText.text ?? "", password: emailPassword.text ?? "", verifyCode: emailVertifyText.text ?? "").onSuccess { (result) in
// The email address is used for sign-up successfully.
}.onFailure { (error) in
// The email address failed to be used for registration.
}
}
Enter the email address and the password you set and tap login to sign in to your app. Congratulations, you have now successfully enabled registration and sign-in with an email address for your app.
Swift:
@IBAction func login(_ sender: Any) {
let credential = AGCEmailAuthProvider.credential(withEmail: emailText.text ?? "", password: emailPassword.text ?? "")
AGCAuth.instance().signIn(credential: credential).onSuccess { (result) in
// Sign-in success.
}.onFailure { (error) in
// Sign-in failed.
}
}
Summary​Auth Service is a service that provides you with a quick and easy way to develop registration and sign-in functions for app. Its lightweight SDK also help you reduce your app’s size.
Reference​More information about Auth Service

Thanks for sharing

Related

Safeguarding user identity through reliable authentication with HUAWEI FIDO

Opportunity
We are living in a very-connected and fast-paced world where everything needs to be fast, efficient, and convenient. Almost everyone uses apps to establish an online presence through different social media platforms or to take advantage of the convenience of availing online products and services. As more people go online and use multiple apps, securing user accounts and verifying user identities are becoming an utmost importance, especially in situations like account sign-in and online transactions. With the limitations and vulnerabilities of using passwords for authenticating user identities, there is a need for a secure user authentication that provides a positive user experience.
{
"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"
}
What is HUAWEI FIDO?
HUAWEI Fast Identity Online (FIDO) enables developers to provide their apps with local biometric authentication capability and online identity verification capability to complement password security. HUAWEI FIDO provides online identity verification capability via FIDO2 Client, which is based on the World Wide Web Consortium’s Web Authentication (WebAuthn) specification.
FIDO2 Client supports both roaming and platform authenticators to enable checking user validity during account sign-in and payment. FIDO2 Client enables online identity verification to help HUAWEI FIDO augment your app’s password security and optimize your app’s usage convenience. The smooth app integration of FIDO2 Client will help developers in implementing HUAWEI FIDO in their apps.
How to integrate FIDO2 Client?
The integration of the FIDO2 Client to your app involves 2 processes. One is a registration process and the other is an authentication process. The following procedures will provide a high-level guide in executing the registration and authentication processes.
Kindly remember that the listed processes must be performed before performing the integration of the FIDO2 Client:
1. Configuring App Information in AppGallery Connect
2. Integrating the HMS SDK
3. Configuring Obfuscation Scrips
To execute the registration process:
1. Acquire a challenge value and related policy from the FIDO server.
Code:
byte[] challengeBytes = SecureRandom.getSeed(16);
2. Initiate the Fido2 registration request.
Code:
PublicKeyCredentialCreationOptions.Builder builder = new PublicKeyCredentialCreationOptions.Builder();
builder.setRp(new PublicKeyCredentialRpEntity(rpId, rpId, null))
.setUser(new PublicKeyCredentialUserEntity(user, user.getBytes()))
.setChallenge(challengeBytes)
.setAttestation(AttestationConveyancePreference.DIRECT)
.setAuthenticatorSelection(new AuthenticatorSelectionCriteria(null, null, null))
.setPubKeyCredParams(new ArrayList<PublicKeyCredentialParameters>(
Arrays.asList(
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, Algorithm.ES256),
new PublicKeyCredentialParameters(PublicKeyCredentialType.PUBLIC_KEY, Algorithm.RS256))))
.setTimeoutSeconds(60L);
if (regCredentialId != null) {
builder.setExcludeList(new ArrayList<PublicKeyCredentialDescriptor>(
Arrays.asList(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, regCredentialId))));
3. Initiate the registration by calling Fido2Client.getRegistrationIntent() to obtain a Fido2Intent instance and start the FIDO client registration process.
Code:
fido2Client.getRegistrationIntent(request, NativeFido2RegistrationOptions.DEFAULT_OPTIONS,
new Fido2IntentCallback() {
@Override
public void onSuccess(Fido2Intent fido2Intent) {
fido2Intent.launchFido2Activity(Fido2DemoActivity.this, Fido2Client.REGISTRATION_REQUEST);
}
@Override
public void onFailure(int errorCode, CharSequence errString) {
showError("Registration failed." + errorCode + "=" + errString);
}
});
The registration starts by calling Fido2Intent.launchFido2Activity() in the callback using Fido2Client.REGISTRATION_REQUEST as requestCode.
4. Receive the registration result by calling Fido2Client.getFido2RegistrationResponse() in the callback Activity.onActivityResult()
Code:
Fido2RegistrationResponse fido2RegistrationResponse = fido2Client.getFido2RegistrationResponse(data);
if (fido2RegistrationResponse.isSuccess()) {
reusltView.append("Registration\n");
reusltView.append(fido2RegistrationResponse.getAuthenticatorAttestationResponse().toJson());
reusltView.append("\n");
regCredentialId = fido2RegistrationResponse.getAuthenticatorAttestationResponse().getCredentialId();
showMsg("Registration successful.");
} else {
showError("Registration failed.", fido2RegistrationResponse);
}
5. Send the registration result to the FIDO Server for verification.
To execute the authentication process:
1. Acquire a challenge value and related policy from the FIDO server.
Code:
byte[] challengeBytes = SecureRandom.getSeed(16);
2. Initiate the Fido2 Authentication request.
Code:
List<PublicKeyCredentialDescriptor> allowList = new ArrayList<>();
allowList.add(new PublicKeyCredentialDescriptor(PublicKeyCredentialType.PUBLIC_KEY, regCredentialId));
PublicKeyCredentialRequestOptions.Builder builder = new PublicKeyCredentialRequestOptions.Builder();
builder.setRpId(rpId).setChallenge(challengeBytes).setAllowList(allowList).setTimeoutSeconds(60L);
return new Fido2AuthenticationRequest(builder.build(), null);
3. Initiate the authentication by calling Fido2Client.getAuthenticationIntent() to obtain the Fido2Intent instance and start the FIDO Client authentication process.
Code:
fido2Client.getAuthenticationIntent(request, NativeFido2AuthenticationOptions.DEFAULT_OPTIONS,
new Fido2IntentCallback() {
@Override
public void onSuccess(Fido2Intent fido2Intent) {
fido2Intent.launchFido2Activity(Fido2DemoActivity.this, Fido2Client.AUTHENTICATION_REQUEST);
}
@Override
public void onFailure(int errorCode, CharSequence errString) {
showError("Authentication failed." + errorCode + "=" + errString);
}
});
The authentication starts by calling Fido2Intent.launchFido2Activity() in the callback using Fido2Client.AUTHENTICATION_REQUEST as requestCode.
4. Receive the authentication response by calling Fido2Client.getFido2AuthenticationResponse() in the callback Activity.onActivityResult().
Code:
Fido2AuthenticationResponse fido2AuthenticationResponse =
fido2Client.getFido2AuthenticationResponse(data);
if (fido2AuthenticationResponse.isSuccess()) {
reusltView.append("Authentication\n");
reusltView.append(fido2AuthenticationResponse.getAuthenticatorAssertionResponse().toJson());
reusltView.append("\n");
showMsg("Authentication successful.");
} else {
showError("Authentication failed.", fido2AuthenticationResponse);
}
5. Send the authentication result to the FIDO server for verification.
The Benefits
To the developers
Provides developers with a high-level guide on integrating the FIDO2 Client so that they could easily implement HUAWEI FIDO to increase the security of their apps.
Related Links
Thanks to Ibrahim Recep Serpici for this article.

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 ?

AppGallery Auth service using Mobile Number [Android]

More information like this, you can visit HUAWEI Developer Forum​
Article Introduction
The following article describes the easiest way to obtain easy, secure, and efficient mobile phone number registration & sign-in using the AppGallery Auth service.
AppGallery Auth Service Introduction
AppGallery Connect provides a cloud-based auth service and SDKs to help you quickly build a secure and reliable user authentication system for your apps to verify user identity.
The AppGallery Connect auth service supports multiple authentication methods and is seamlessly integrated with other Serverless services to help you secure user data based on simple rules that you have defined.
In this article, we will cover just the mobile number authentication method in Android.
Integrating the Auth Service SDK
Before start using the AppGallery Auth Service, we must first integrate the Auth Service SDK by following the steps below :
Step 1:
Create an app in AppGallery Connect and integrate the AppGallery Connect SDK into your app. For details, please refer to AppGallery Connect Service Getting Started.
Step 2:
Add the Auth Service dependencies in the build.gradle file in the app directory (usually app/build.gradle).
Code:
implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
Enabling Auth Service
we must also enable the Auth Service in AppGallery Connect by following the steps below :
Step 1:
Sign in to AppGallery Connect and select My projects.
Step 2:
Find your project from the project list and click the app for which you need to enable Auth Service on the project card.
Step 3:
Go to Build > Auth Service. If it is the first time that you use Authe Service, click Enable now in the upper right corner.
{
"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"
}
Step 4:
Click Enable in the row of Mobile number authentication mode to be enabled.
Step 5: (optional)
Configure the SMS template which supports multilingual configuration: Auth Service > settings > Verification code and notification template settings.
Coding
There're five major client-side methods:
SendOTP.
SignUp.
SignIn.
Get the current user.
SignOut.
SendOTP:
Used to apply for verification code for mobile number +[countryCode][phoneNumber]
Code:
private void sendOTP(){
VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
.action(ACTION_REGISTER_LOGIN) //ACTION_REGISTER_LOGIN/ACTION_RESET_PASSWORD
.sendInterval(30) // Minimum sending interval, which ranges from 30s to 120s.
.locale(Locale.getDefault()) // Optional. It indicates the language for sending a verification code.
.build();
Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countryCode, phoneNumber, settings);
task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
@Override
public void onSuccess(VerifyCodeResult verifyCodeResult) {
// The verification code application is successful.
Log.i(TAG, "onSuccess: "+verifyCodeResult.toString());
}
}).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "onFailure: ");
}
});
}
SignUp:
Used to register a new user using a mobile number +[countryCode][phoneNumber]
Code:
private void signUp(){
PhoneUser phoneUser = new PhoneUser.Builder()
.setCountryCode(countryCode)//ex: 212
.setPhoneNumber(phoneNumber)//ex: 698841421
.setVerifyCode(OTP)//OTP sent via the sendOTP() method
.setPassword(null)
.build();
AGConnectAuth.getInstance().createUser(phoneUser)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
Log.i(TAG, "onSuccess SignUp: "+signInResult.toString());
// The user is registered and you can add any logic you want
// After that, the user has signed in by default.
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "onFailure SignUp: "+e.getMessage());
// there's an issue (the user already registered ...)
}
});
}
Note 1: Before registering the User, he must obtain the OTP using the sendOTP() method above.
Note 2: After the registration is successful, the user signs in automatically. no need to call the SignIn method.
Note 3: If the user is already registered, the onFailureListener will be triggered.
SignIn:
Used to sign-in the user after obtaining his credential from the AppGallery Connect server.
Code:
private void SignIn(){
AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, null , OTP);
AGConnectAuth.getInstance().signIn(credential)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// Obtain sign-in information.
Log.i(TAG, "onSuccess: login"+signInResult.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "onFailure: login"+e.getMessage());
}
});
}
Note: Before logging in, the user must obtain the OTP using the sendOTP() method above.
Get the current user:
This method is used to get the currently signed-in user.
Code:
private AGConnectUser getCurrentUser(){
return AGConnectAuth.getInstance().getCurrentUser();
}
SignOut:
This method is used to sign-out the currently signed-in user.
Code:
private void signOut(){
if(getCurrentUser()!=null)
AGConnectAuth.getInstance().signOut();
}
References
AppGallery Auth Service:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-auth-service-introduction
Conclusion
Integrating the AppGallery Auth service is the right choice to allow users to use mobile phone numbers to connect to your application securely, easily, and efficiently, without wasting much time and effort building the Auth functionality from scratch.
How to handle region based mobile numbers.
How can I implement a smart lock for passwords?
Thank you very much
Excellent guide, very intuitive, truly detailed and with all the information needed
How much time it takes for OTP to expire?
How much time it will take to integrate service completely ?
Interesting feature. It seems easy to integrate it.
Interesting, excellent guide

Working with Huawei Account Kit on Flutter Projects

In this article, we’ll be looking at some of the APIs that Account Kit provides and learn how to use them in our Flutter projects.
Huawei Account Kit
Account Kit provides a simple and quick authorization experience to users. It enables to save time from long authorization periods and it’s two factor authentication process keeps users information safe. Account Kit allows you to connect to the Huawei ecosystem using your Huawei Id from a range of devices, such as mobile phones and tablets. Users can quickly and conveniently sign in to apps with their Huawei Ids after granting an initial access permission.
Configuring the project
Registering as a Developer
As first, you need to create a Huawei developer account and complete the identity verification. For details, please refer to Registering a Huawei Id.
Creating an APP
Sign in AppGallery Connect and create a new project.
Add a new app to your project by clicking the Add App button.
{
"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"
}
Generating a Signing Certificate Fingerprinter
Signing certificate fingerprints are used to verify the authenticity of an App when it attempts to access an HMS Core service through the HMS Core SDK. So before using the HMS Core service, you must generate a signing certificate fingerprint and configure it in AppGallery Connect.
Generate a Signing Certificate by referring here.
Then you’ll need to export the SHA256 Fingerprint by using keytool provided by JDK. You can find detailed steps here.
Adding Fingerprint Certificate to AppGallery Connect
On the application information page of the project, click to add your SHA256 fingerprint. Then click ✓ to save fingerprint.
Enabling Account Kit Service
On the application information page, click Manage APIs and make sure Account Kit is enabled.
Integrating HMS and Account Plugin to Flutter Project
Open pubspec.yaml file of your project and add Huawei Account Plugin as a dependency.
Code:
dependencies:
flutter:
sdk: flutter
huawei_account: ^5.0.0+300
Download agconnect-services.json file from application information page.
Move the file to the android/app directory with the signing certificate file you’ve created.
Open the android/build.gradle file and configure the Maven repository address and agconnect plugin for the HMS Core SDK.
Code:
buildscript {
repositories {
// Other repositories
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
// Other dependencies
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
// Other repositories
maven { url 'https://developer.huawei.com/repo/' }
}
}
Add the AppGallery Connect plugin to your app level build.gradle file.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
Then add the signing configurations in the same file. Don’t forget that your applicationId must be same as the one you created in AppGallery Connect. Also change your minSdkVersion to 19.
Code:
android {
defaultConfig {
applicationId "<application_id>"
minSdkVersion 19
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
signingConfigs {
config {
storeFile file('<keystore_file>')
storePassword '<keystore_password>'
keyAlias '<key_alias>'
keyPassword '<key_password>'
}
}
buildTypes {
debug {
signingConfig signingConfigs.config
}
release {
signingConfig signingConfigs.config
}
}
}
Now we’re done with the integration part and ready to use the Account Plugin in our application.
Using Huawei Account Kit Flutter Plugin
Setting Up The Authorization
Account Plugin allows you to customize the authorization. You can request users to authorize their email addresses, profile information or access tokens. To accomplish that, you can use AuthParamHelper class.
Create an instance of AuthParamHelper class. Then set the parameters you want to customize.
Code:
AuthParamHelper helper = new AuthParamHelper();
// You can set many options by using cascades
helper..setEmail()..setRequestCode(8888);
Signing In
Now we’re going to call signIn method through HmsAccount class and pass our helper instance to it. In return, this method gives us the Huawei Id information through AuthHuaweiId class.
Code:
try {
// Make sure you handle the possible exceptions.
final AuthHuaweiId authHuaweiId = await HmsAccount.signIn(helper);
} on Exception catch (e) {
print(e.toString());
}
As this method is triggered, an authorization screen shows up. After clicking the login button, you can see the Huawei Id information is received.
Account Plugin has signOut method which clears the user’s Huawei Id information when it comes to sign out from an app. But the information is not permanently deleted.
Code:
try {
// Make sure you handle possible exceptions.
final bool result = await HmsAccount.signOut();
} on Exception catch (e) {
print(e.toString());
}
Revoking Authorization
After signing in for the first time, when users try to sign in again, the authorization screen will not show up unless users revoke it. Huawei Id information will be received directly. Once the authorization is revoked, logged id information will be deleted. And the authorization screen will be shown on another login attempt.
Code:
try {
// Make sure you handle possible exceptions.
final bool result = await HmsAccount.revokeAuthorization();
} on Exception catch (e) {
print(e.toString());
}
Sms Verification
One of the options that Account Plugin provides us is the sms verification. This service can catch sms messages in certain formats. Unlike the other authorization methods, you should be able to send sms messages for this special service.
Obtaining Application’s Hash Code
To catch upcoming sms messages, we need to know the hash code value which is unique in each app. Account Plugin provides obtainHashcode method to get that.
Code:
try {
// Make sure you handle possible exceptions.
final String hashcode = await HmsAccount.obtainHashCode();
} on Exception catch (e) {
print(e.toString());
}
Sending Sms Messages
The messages you’ll send should be as follows:
Code:
prefix_flag short message verification code is ****** hash_code
prefix_flag indicates the prefix of an SMS message, which can be <#>, [#], or \u200b\u200b. \u200b\u200b are invisible Unicode characters.
short message verification code is indicates the content of an SMS message, which is user-defined.
****** indicates the verification code.
Receiving Sms Messages
Account Plugin comes with smsVerification method to listen and catch the right formatted messages. Once it is called, the app starts listening. Waits for the messages for five minutes before timing out. Returns the message or error code depending on the situation.
Code:
HmsAccount.smsVerification(({errorCode, message}){
if (message != null) {
// Use the message
} else {
print("Error: $errorCode");
}
});
It’s all done. Now you’re ready to use Account Plugin in your Flutter applications.
Conclusion
Huawei Account Kit is such an easy and secure way to carry out authorization processes, along many other kits with powerful solutions. I think these services will keep providing a nice experience for both developers and users as they get bigger and better.
You can check some other articles about Hms Core Plugins below, and feel free to ask any question about this article in the comments.

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

Categories

Resources