AppGallery Auth service using Mobile Number [Android] - Huawei Developers

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

Related

Implement Health Kit in Java in 10 minute

More articles like this, you can visit HUAWEI Developer Forum​
Want to retrieve health or fitness data of users based on their HUAWEI ID and show in your app?
{
"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"
}
​
Health Kit provide main three feature:
Data storage
Provides a data platform for developers to store fitness and health data.
Data openness
Provides a wide range of fitness and health APIs and supports sharing of the various fitness and health data, including step count, weight, and heart rate.
Data access authorization management
Provides settings for users and developers so users can manage developer's access to their health and fitness data, guaranteeing users' data privacy and legal rights.
Developement
1.Register HUAWEI ID and apply for Account Service*
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-id-0000001050069756
2. Applying for Health Kit in developer console*
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-kitservice-0000001050071707
3. Integrate HMS Health Kit
In Build.gradle file,add the implementation.
Code:
implementation 'com.huawei.hms:hihealth-base:{5.0.0.300}
In AndroidManifest.xml file, add the app ID generated when the creating the app on HUAWEI Developers to the application section.
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="APP ID"/>
4.Call the related APIs to display HUAWEI ID sign-in screen and authorization screen. The app can only access data upon user authorization.
Sign in via HMS Core SDK and apply for the scope to obtain the permissions to access the HUAWEI Health Kit APIs.
Code:
private void signInn() {
Log.i(TAG, "begin sign in");
List<Scope> scopeList = new ArrayList<>();
// Add scopes to apply for. The following only shows an example.
// Developers need to add scopes according to their specific needs.
// View and save steps in HUAWEI Health Kit.
scopeList.add(new Scope( Scopes.HEALTHKIT_STEP_BOTH));
// View and save height and weight in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_CALORIES_BOTH));
// View and save the heart rate data in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_DISTANCE_BOTH));
// Configure authorization parameters.
HuaweiIdAuthParamsHelper authParamsHelper =
new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM);
HuaweiIdAuthParams authParams =
authParamsHelper.setIdToken().setAccessToken().setScopeList(scopeList).createParams();
// Initialize the HuaweiIdAuthService object.
final HuaweiIdAuthService authService =
HuaweiIdAuthManager.getService(this.getContext(), authParams);
// Silent sign-in. If authorization has been granted by the current account,
// the authorization screen will not display. This is an asynchronous method.
Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn();
final Context context = this.getContext();
// Add the callback for the call result.
authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId huaweiId) {
// The silent sign-in is successful.
Log.i(TAG, "silentSignIn success");
try {
readData();
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(context, "silentSignIn success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception exception) {
// The silent sign-in fails.
// This indicates that the authorization has not been granted by the current account.
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
Log.i(TAG, "begin sign in by intent");
// Call the sign-in API using the getSignInIntent() method.
Intent signInIntent = authService.getSignInIntent();
MeFragment.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
}
}
});
}
5.Build the condition for data query: a DataCollector object
Code:
DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build();
6.Build time range and build condition-based query object.
Use the specified condition query object(call read Option) to call the data controller to query the sampling dataset.
Code:
public void readData() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-07-17 09:05:00");
ReadOptions readOptions = new ReadOptions.Builder()
.read(DataType.DT_CONTINUOUS_STEPS_DELTA)
.read(DataType.DT_CONTINUOUS_CALORIES_BURNT)
.read(DataType.DT_CONTINUOUS_DISTANCE_DELTA)
.setTimeRange(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
.build();
Task<ReadReply> readReplyTask = dataController.read(readOptions);
readReplyTask.addOnSuccessListener(new OnSuccessListener<ReadReply>() {
@Override
public void onSuccess(ReadReply readReply) {
for (SampleSet sampleSet : readReply.getSampleSets()) {
showSampleSet(sampleSet);
Log.i(TAG,"*****************"+sampleSet);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
checkData.setText(e.toString()+"read");
}
});
}
7.the calories,distance and step are succesfully show in app.
Reference:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/overview-dev-android-0000001050071671

HUAWEI Game Service Implementation : Events

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Huawei Game service provides a centralized place for you to manage game services and configure metadata for authorizing and authenticating your game. Using Huawei game service, developer can access range of capabilities to help develop your games more efficiently.
Features
1. Developers can promote their game efficiently and quickly.
2. Developers can easily build the foundation of game by implementing features like achievements and events.
3. Developers can perform in-depth operations tailored to their game and their users.
In this article, we will implement event feature provided by Huawei game service in Tic tac toe game.
{
"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"
}
Prerequisites
1. Developer has created an application on App Gallery Connect. Follow Creating an App.
2. Integrating app gallery connect SDK. Please refer to AppGallery Connect Service Getting Started.
3. Developer has integrated Huawei Account kit. Follow this tutorial to integrate account kit.
4. HUAWEI mobile phone with HMS Core 4.0.0.300 or later installed.
Setup:
1. Enable Huawei Game service in Manage APIS. Please refer to Service Enabling.
2. Add appgallery connect plug-in in app-level build.gradle
Code:
apply plugin: 'com.huawei.agconnect'
3. Add following dependencies in app-level build.gradle and click on Sync Now and wait till synchronization is done.
Code:
dependencies {
implementation 'com.huawei.hms:base:4.0.4.301'
implementation 'com.huawei.hms:hwid:4.0.4.300'
implementation 'com.huawei.hms:iap:4.0.4.300'
implementation 'com.huawei.hms:game:4.0.3.301'
}
Initialization
Once Initial set up is done, let’s implement Huawei game service in Tic tac toe game
1. Add the following code in onCreate() method of Application class.
Code:
public class GameServiceApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
HuaweiMobileServicesUtil.setApplication(this);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
2. To initialize the game
Code:
private void init() {
JosAppsClient appsClient = JosApps.getJosAppsClient(this, null);
appsClient.init();
Log.i(TAG, "initialization success");
}
Signin In
1. When app is launched, Huawei sign-in page is displayed.
2. User enters Huawei Huawei ID and password to sign in.
3. After a successful sign in, the app obtains player information corresponding to Huawei ID.
Please refer to this article for sign in implementation.
Game Events
The Game events allow developer to collect specific data generated by players and store them on Huawei game server for AppGallery connect. In this article, we will collect data pertaining to player win. Every time players win the match, we will store it in Huawei game server.
Creating an Event in AppGallery Connect
1. Sign in to AppGallery Connect and select My apps.
2. Select an app from the app list to create an event.
3. Click the Operate tab and go to Products > Game Event. Click Create.
4. Configure the event information and click Save.
5. Check your event ID on the event list and properly save the ID for event development.
Implementation of Event
1. To initialize EventsClient instance
Code:
EventsClient client = Games.getEventsClient(this, mAuthHuaweiId);
mAuthHuaweiId is obtained during sign in.
2. To submit the event
Code:
client.grow(eventId, growAmount);
eventId indicates the ID of the event which is generated while defining the event in AppGallery connect. In our app we will submit the event everytime players win the match.
The growAmount parameter specifies an increment amount of the event value.
To Obtain Events
Following code can be used to obtain the events.
Code:
Task<List<Event>> task = client.getEventList(forceReload);
forceReload is a Boolean type used to indicate whether to obtain data stored on the Huawei game server or locally cached data.
Following code shows how list of events are returned.
Code:
task.addOnSuccessListener(new OnSuccessListener<List<Event>>() {
@Override
public void onSuccess(List<Event> data) {
if (data == null) {
Log.w("Event", "event is null");
return;
}
for (Event event : data) {
Log.i("Event", "event id:" + event.getEventId());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
if (e instanceof ApiException) {
String result = "errorCode:"
+ ((ApiException) e).getStatusCode();
Log.e("Event", result);
}
}
});
We will show the retrieved events list in recyclerview. Clicking on event list item will show details about the events.
Code:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Event event = eventList.get(position);
final String eventId = event.getEventId();
Glide.with(context).load(event.getThumbnailUri()).into(holder.eventImage);
holder.eventName.setText(event.getName());
holder.eventAmonut.setText("value:"+event.getValue() + "#" + event.getLocaleValue());
holder.eventDes.setText(event.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.onItemClick(position);
}
});
holder.eventReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.reportEvent(eventId);
}
});
}
Screenshots
​ Summary
In this article, we understood initial setup and game event features of Huawei Game Service. In next article, we will discuss more features provided by Huawei Game service.
Source code can be downloaded from https://github.com/DTSE-India-Community/Huawei-Game-Service
How many days it will take to get data reflected in AGC.

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.

Make Users to Update Your Application with HMS

{
"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"
}
AppGalleryKit App and AppGalleryKit Game services allows to jointly operate the apps with Huawei and share revenue generated in the process. Developer will have access to Huawei’s diverse services including HUAWEI AppGallery connection, data reports, activity operations, and user operations to obtain more premium HUAWEI AppGallery resources in order to promotion purposes.
To enable AppGalleryKit App or AppGalleryKitGame operations, you need to sign the HUAWEI AppGallery Connect Distribution Service Agreement For Paid Apps with Huawei. For details about the joint operations process, please refer to Joint Operations Services at a Glance.
AppGalleryKit App and AppGalleryKit Game is a product concept derived from Account, Analytics, In-App Purchases and other kits. With AppGalleryKit App or AppGalleryKit Game, initializing the app, updating the app, implementing Account Kit is optional. But it is necessary to implementing In-App Purchases kit to use AppGalleryKit App or AppGalleryKit Game. Also it is advised that use Analytics Kit, Auth Service, Crash Service, A/B Testing and APM.
AppGalleryKitApp or AppGalleryKitGame is not pure kit integration. It is required for developers to sign AppGalleryKitApp or AppGalleryKitGame related agreements and they are derived from many features.
Initiliazing app, updating the app, Account Kit and In-App Purchases can be implemented seperately. These kits do not depend on AppGalleryKitApp or AppGalleryKitGame. But AppGalleryKitApp or AppGalleryKitGame depends on these kits.
Although we are not going to use AppGalleryKitApp or AppGalleryKit game, we can still use the update status of the application. In this article, we will check if there is an update in a demo app. Of course due to this app will not be in AppGallery market, there will not any update required.
In order to use this feature, first HMS Core is needed to be integrated to the project.
You can click this link to integrate HMS Core to your project.
Adding Dependency
After HMS Core is integrated, app-service library needs to be implemented.
Code:
implementation 'com.huawei.hms:appservice:{version}' // Currently version is 5.0.4.302
We will create a checkUpdate method and use it in onCreate. JosApps.getAppUpdateClient method, AppUpdateClient instance will be obtained. This object provides the methods related to app update. checkAppUpdate method, checks for app updates after the app is launched and initialized.
Java:
private void checkUpdate(){
AppUpdateClient client = JosApps.getAppUpdateClient(this);
client.checkAppUpdate(this, new UpdateCallBack(this));
}
We need to create a static class which is UpdateCallBack and it will implement CheckUpdateCallBack. CheckUpdateCallBack returns a result for checking for app updates. It requires onUpdateInfo, onMarketInstallInfo, onMarketStoreError and onUpdateStoreError methods are implemented.
in onUpdateInfo method, we can get status code, fail code, fail reason and other informations.
For more information you can click this link.
Code:
private static class UpdateCallBack implements CheckUpdateCallBack {
private final WeakReference<MainActivity> weakMainActivity;
private UpdateCallBack(MainActivity mainActivity) {
this.weakMainActivity = new WeakReference<>(mainActivity);
}
public void onUpdateInfo(Intent intent) {
if (intent != null) {
MainActivity mainActivity = null;
if (weakMainActivity.get() != null){
mainActivity = weakMainActivity.get();
}
int status = intent.getIntExtra(UpdateKey.STATUS, 100);
int rtnCode = intent.getIntExtra(UpdateKey.FAIL_CODE, 200);
String rtnMessage = intent.getStringExtra(UpdateKey.FAIL_REASON);
Serializable info = intent.getSerializableExtra(UpdateKey.INFO);
if (info instanceof ApkUpgradeInfo && mainActivity != null ) {
AppUpdateClient client = JosApps.getAppUpdateClient(mainActivity);
//Force Update option is selected as false.
client.showUpdateDialog(mainActivity, (ApkUpgradeInfo) info, false);
Log.i("AppGalleryKit", "checkUpdatePop success");
}
if(mainActivity != null) {
//status --> 3: constant value NO_UPGRADE_INFO, indicating that no update is available.
Log.i("AppGalleryKit","onUpdateInfo status: " + status + ", rtnCode: "
+ rtnCode + ", rtnMessage: " + rtnMessage);
}
}
}
@Override
public void onMarketInstallInfo(Intent intent) {
//onMarketInstallInfo
}
@Override
public void onMarketStoreError(int i) {
//onMarketStoreError
}
@Override
public void onUpdateStoreError(int i) {
//onUpdateStoreError
}
}
In this example, due to we do not have the application released in the market, we got a status code which is equal to 3. This indicates that for the application there is no upgrade needed.
For all status codes, you can check the below image.
For more details, you can check AppGalleryKit App and AppGalleryKit Game development guide links in reference section. Also you can download this demo application from the Github link.
Reference
AppGalleryKit App
AppGalleryKit Game
Github

【Integration Guide】 HUAWEI Account Kit Demo

In the previous post, we learned the advantages of Account Kit: one-click sign-in authorization in any scenario, secure and reliable services, and convenient integration, as well as giving apps access to the global HUAWEI ID base of potential users. A QR code is also provided at the end of the post for you to download the demo app to experience HUAWEI ID sign-in authorization. The demo has integrated three Account Kit APIs (four in total), and is easy to develop. In this article, we'll show you the demo development to get you familiar with Account Kit.
Before you start, use a browser to scan the QR code below to try the demo app.
{
"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: The app may collect relevant information for user statistics.)
Preparing for Demo Development​l Install Android Studio 3.5 or later.
l Install JDK 1.8 or later.
l Use SDK Platform 19 or later.
l Use Gradle 4.6 or later.
l If you haven't already, register as a developer on HUAWEI Developers.
l Download the sample code of the demo from GitHub.
Configuring the Running Environment (2 minutes)​1. Use Android Studio to open the demo project.
2. Go to File > Settings > Plugins > Marketplace, enter HMS Toolkit in the search box, and click Install. Note: HMS Toolkit must be version 5.2.0.300 or later.
For details, please refer to Installing HMS Toolkit.
3. Create a package and rename it to something like com.hxb.account in the project. Then, copy the code in the com.huawei.hms.accountsample package to your package, and change the value of package and applicationId to your package name. (Do not use the existing package name in the demo project because it is already registered on HUAWEI AppGallery.)
First, create a package. Move the MainActivity class to your package so that you can search for related files easily during the build.
Change package in the AndroidManifest.xml file to com.hxb.account.
Change applicationId in the build.gradle file to com.hxb.account.
4. Go to HMS > Configuration Wizard to check the environment configuration. If you have not signed in with a HUAWEI ID, Toolkit will first prompt you to do so.
On the Configuration Wizard page displayed, you are prompted that no app corresponding to the package name was detected under the signed-in HUAWEI ID.
Click Link to go to AppGallery Connect and create an app manually:
(a) Click Release.
(b) Click Add project.
(c) Create a project.
(d) Click Add app.
(e) Add the project.
After creating, go back to the Configuration Wizard page and click Retry. This time, the check will be successful.
5. Choose Account Kit.
On the Configuration Wizard page, click Add Kits and choose Account Kit.
The following page will be displayed.
6. Choose a certificate. You can choose Use Android debug certificate and click Generate to generate a certificate fingerprint, as shown in the following figure.
7. Click Next to automatically complete other configurations including toggling on the Account Kit switch in AppGallery Connect, configuring the signing certificate fingerprint, downloading the agconnect-services.json file to the project directory, configuring obfuscation scripts, and adding build dependencies and APK fingerprint required for integrating the Account SDK to the build.gradle file. Once these configurations are completed, the following page will be displayed. If you run into errors, please refer to the corresponding guide on the page.
Packaging and Testing the Demo on Remote Real Device Provided by Toolkit​After configuration, go to HMS > Cloud Debugging to package and test the demo app.
Select the desired device model.
Click Run to test the demo app.
Key Code for Demo Development​1. UI Design
Account Kit provides four main APIs for signing in, silently signing in, revoking authorization, and signing out. The demo app integrates the first three.
In the above figure, the Sign in with HUAWEI ID button is created with an encapsulated standard control. Please follow HUAWEI ID Sign-In Button Usage Rules when using the icon elements provided by Huawei.
Code:
<p style="line-height: 1.5em;"><com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
/>
1. Key Code for APIs
(1) Sign-in
Use case: Account Kit, compliant with OAuth 2.0 and OpenID Connect, supports sign-in in two modes: authorization code (for apps with their own servers only) and ID token modes. Select the mode you need.
Code:
private void signIn() {
mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams();
mAuthManager = AccountAuthManager.getService(AccountActivity.this, mAuthParam);
startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
}
As shown, setIdToken() means use the ID token mode for authorization. The other mode will show setAuthorizationCode() instead. Their difference will be described later. getSignInIntent() is the API for ID sign-in authorization.
Process the result after authorization.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
// Successful sign-in.
// Obtain user information through parseAuthResultFromIntent.
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
AuthAccount authAccount = authAccountTask.getResult();
Log.i(TAG, authAccount.getDisplayName() + " signIn success ");
Log.i(TAG, "AccessToken:\n" + authAccount.getAccessToken());
Log.i(TAG, "OpenId:\n" + authAccount.getOpenId());
Log.i(TAG, "Email:\n" + authAccount.getEmail());
Log.i(TAG, "UnionId:\n" + authAccount.getUnionId());
// Download avatar by using AsyncTask.
NetService = new NetService(new URLPostHandler() {
@Override
public void PostHandler(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
textView.setText(authAccount.getDisplayName());
}
});
netService.execute(authAccount.getAvatarUriString());
} else {
Log.i(TAG, "signIn failed: " + ((ApiException)
authAccountTask.getException()).getStatusCode());
}
}
}
(2) Silent sign-in
Use case: Authorization is required only on first sign-in to your app using a HUAWEI ID. Subsequent sign-ins using the same HUAWEI ID do not require any authorization.
Code:
private void silentSignIn() {
Task<AuthAccount> task = mAuthManager.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
Log.i(TAG, "silentSignIn success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// If failed, use getSignInIntent.
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
signIn();
}
}
});
}
Call silentSignIn() to implement silent sign-in.
(3) Authorization revoking
Use case: To improve privacy security, users can unauthorize your app.
Code:
private void cancelAuthorization() {
Task<Void> task = mAuthManager.cancelAuthorization();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
imageView.setImageDrawable(null);
textView.setText("");
Log.i(TAG, "cancelAuthorization success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "cancelAuthorization failure:" + e.getClass().getSimpleName());
}
});
}
Call cancelAuthorization() to revoke authorization.
For more information about Account Kit, please visit:
l Development guide
l Codelab
l Video course (and the course for HMS Core 4.0.)
For more details, you can go to:
Our official website
Demo of Analytics Kit
Android SDK integration documentation
iOS SDK integration documentation
Web SDK integration documentation
Quick app SDK integration documentation
Checkout in forum

Categories

Resources