Gigya Job Openings

Android SDK v4

Skip to end of metadata
Go to start of metadata

 

Description

Gigya's Android SDK library provides a Java interface for Gigya's API - It allows simplified integration and usage within your Android application life-cycle.

This document is a practical step-by-step guide for integrating & utilizing Gigya's services within the extent of your Android native application.

Code examples will be provided in both Java & in Kotlin.

The Android SDK v4 was tested on Android Q Beta but does not officially support it. Support of Android Q will be official once it is released.

 

Download the SDK and Associated Files

Download the latest Android SDK files below:

Gigya Developer Downloads

 

If you are upgrading from a previous version, please make sure to read the SDK's Change Log.

 

Why Should I Upgrade

Gigya's Android SDK v4.0.x is a complete redesign of the previous Android SDK version.

  When we approached it, we first consulted the developers that experienced its implementation in their mobile app and together we defined 3 leading aspects to it:

  • Aligned with up-to-date development and performance standards
  • Great customer development experience (never leave the IDE)
  • Focus on common business flows

So, with CDC Android SDK v4, you'll enjoy the following benefits:

  • Better performance.
  • Easy work with you site's custom account schema as it's now easily integrated with the entire SDK.
  • Caching of the end-user's account data to reduce network calls.
  • Built-in business flows, like registration, login and more, with out-of-the-box handling for the different outcome scenarios.
    • For example, an end-user tries to register and gets "pending registration" due to a missing required field configured in the site's schema.

 

Sample Applications

Several sample applications which contain most of the available features is available for download in Java & in Kotlin:

While the Java project is a playground project intended for testing and feature-first experience, you can find in the Kotlin project references to most of the features available in the SDK. 

Both projects are regularly updated and independently maintained.

Gigya Developer Downloads

 

Basic Integration

In order to include the CDC Android SDK in your project, download it and place the .AAR file in your application  libs/  folder. 

  Afterwards, add the following to your build.gradle file:

implementation files('libs/gigya-android-sdk-4.0.1.aar')
implementation 'com.google.code.gson:gson:2.8.5' // required dependency of the SDK
  
implementation files('libs/gigya-android-biometric-1.0.1.aar') // Optional. Biometric fingerprint authentication.
implementation 'com.android.support.design:28.0.0' // Optional. Required for using biometric fingerprint authentication.

 

AndroidMainfest XML

Paste the following lines to your application's AndroidManifest.xml  file:

  • To add the most basic permissions required:

    <uses-permission android:name="android.permission.INTERNET"/>
  • For complete CDC SDK  HostActivity   WebLoginActivity  references:

    <activity
        android:name="com.gigya.android.sdk.ui.HostActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@style/Theme.AppCompat.Translucent" />
    
    <activity
        android:name="com.gigya.android.sdk.ui.WebLoginActivity"
        android:allowTaskReparenting="true"
        android:launchMode="singleTask"
        android:theme="@style/Theme.AppCompat.Translucent">
        <intent-filter android:label="web_login_redirect">
            <action android:name="android.intent.action.VIEW" />
    
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:host="gsapi"
                android:pathPrefix="/YOUR-PACAKGE-NAME/login_result"
                android:scheme="gigya" />
        </intent-filter>
    </activity>


Styles XML

Paste the following lines to your styles.xml  file:

<style name="Theme.AppCompat.Translucent" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
</style>

The Android SDK uses Android's  AppCompat  library, therefore, the above style is required

  Alternatively, you can change the theme of the HostActivity & WebLoginActivity to a custom style, however, it is still recommended to apply translucency.

 

Initialization

In order to initialize the SDK please add the following lines in your Application extension class.

Example can be viewed in the Sample Apps, within the GigyaSampleApplication class.

 

Java

/*
Attaching the application context reference.
*/
Gigya.setApplication(this);
  
/*
Initializing the SDK. Account schema will be set to GigyaAccount.class.
*/
Gigya.getInstance();
  
/*
Initializing the SDK with a custom account schema.
*/
Gigya.getInstance(MyAccount.class);

 

Implicit Initialization

The SDK will implicitly initialize itself according to one of the following:

  • JSON file 
  • AndroidManifest.xml file.

You can only apply one of these methods.

Via JSON configuration file:

You can add a JSON file named "gigyaSdkConfiguration.json" to your application assets folder. 
This will allow the SDK to parse the required configuration fields (ApiKey, ApiDomain, etc) implicitly.

For example:

{
  "apiKey": "3_l7zxNcj4vhu8tLzYafUnKDSA4VsOVNzR4VnclcC6VKsXXmQdq950uC-zY7Vsu9RC",
  "apiDomain": "us1.gigya.com",
  "accountCacheTime": 1,
  "sessionVerificationInterval": 60
}

Via meta-data tags in AndroidManifest.xml:

Alternatively, you are able to add these specific meta-data tags in your AndroidManifest.xml file:

<meta-data
    android:name="apiKey"
    android:value="3_l7zxNcj4vhu8tLzYafUnKDSA4VsOVNzR4VnclcC6VKsXXmQdq950uC-zY7Vsu9RC" />
 
<meta-data
    android:name="apiDomain"
    android:value="us1.gigya.com"/>
  
<meta-data
    android:name="accountCacheTime"
    android:value="1"/>
 
<meta-data
    android:name="sessionVerificationInterval"
    android:value="60" />

" accountCacheTime " & " sessionVerificationInterval " will be explained in detail in the  Account Handling  section of this document.

Explicit Initialization

As an alternative to implicit initialization, you can initialize the SDK explicitly:

 

Java

/*
Using default domain (us1-gigya.com).
*/
Gigya.getInstance(getApplicationContext(), MyAccount.class).init("YOUR-API-KEY");
 
/*
Supplying Api-Key & Api-Domain
*/
Gigya.getInstance(getApplicationContext(), MyAccount.class).init("YOUR-API-KEY", "YOUR-API-DOMAIN");

From this point, code blocks will use the  Gigya  interface as member variable ( mGigya ), as if it was already initialized.

Sending a Request

You can send anonymous requests to Gigya using the SDK using one of two overloads:

  • General - this will return an instance of GigyaApiResponse class (see the section below on how to access its data).
  • Typed - this will return an instance of the provided class.

The following example sends an "accounts.verifyLogin" request using the current logged in user's UID field to verify that the current session is still valid.

 

Java

/*
Setup a map of parameters.
*/
final Map<String,Object> params = new HashMap<>();
params.put("UID", "YOUR-ACCOUNT-UID");
  
/*
Sending "verifyLogin" REST api.
*/
final String API = "accounts.verifyLogin";
  
/*
Send a POST request. Will receive a general purpose GigyaApiResponse.class object in the success block.
*/
mGigya.send(API, params, new GigyaCallback<GigyaApiResponse>() {
    @Override
    public void onSuccess(GigyaApiResponse obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }  
});
  
/*
Send a typed POST request. Will receive parsed MyAccount object in the success block.
RestAdapter.GET is also available depending on the api in question.
*/
mGigya.send(API, params, RestAdapter.POST, MyAccount.class, new GigyaCallback<MyAccount>() {
    @Override
    public void onSuccess(GigyaAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }  
});

You can find the list of available Gigya API endpoints and their required parameters in the  REST API Reference.

The GigyaApiResponse Class

The SDK provides a custom response class for encapsulating Gigya API's responses. 
This class exposes multiple methods that can help simplify your flow.

Here are a few examples of  a given response:

 

Java

private void evaluateGigyaResponse(GigyaApiResponse response) {
     
    // Get JSON formatted response String.
    final String JSON = response.asJson();
  
    // Get response error code.
    final int errorCode = response.getErrorCode();
  
    // Get the account profile (optional: if response was from an account related API)
    final Profile gigyaProfile = response.getField("profile", Profile.class);
    final String firstName = response.getField("profile.firstName", String.class);
  
    // Parse to the response data to a MyAccount class instance (optional: if response was from an account related API)
    final MyAccount myAccount = response.parseTo(MyAccount.class);
}

 

Login & Registration

Site login & registration via API calls (to differ from social login & registration) is available using the login/register methods.

These two actions will eventually end with calling the GigyaLoginCallback, so we'll start with it:

Site Login & Registration

Here are a few examples for login/register usage: 

Login via loginID & password:

 

Java

mGigya.login("LOGIN-ID", "PASSWORD", new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

Register via email & password:

 

Java

/*
Defining custom parameters for the request. In this case setting the session expiration to 10 minutes.
*/
final Map<String, Object> params = new HashMap<>();
params.put("sessionExpiration", 10);
 
mGigya.register("email", "password", params, new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

Social Login

Logging-in using a social network is one of the key features of the Gigya Android SDK.

The following social providers currently support the login operation:

  • Amazon
  • Blogger
  • Facebook
  • FourSquare
  • GooglePlus
  • Instagram
  • Kakao
  • LINE
  • LinkedIn
  • Livedoor
  • Messenger
  • mixi
  • Naver
  • Netlog
  • Odnoklassniki
  • Orange France
  • PayPalOAuth
  • Tencent QQ
  • Renren
  • Sina Weibo
  • Spiceworks
  • Twitter
  • VKontakte
  • WeChat
  • WordPress
  • Xing
  • Yahoo
  • Yahoo Japan

 

All supported providers constants are available using  GigyaDefinitions.Providers  class.

The following providers support native login using their own SDKs:

  • Facebook
  • Google
  • Line
  • WeChat

Please make sure to follow each configuration implementation mentioned in the Configuring Native Login section.

While native support will require you to add the provider's library dependency to your application's build.gradle file, for Google Sign-In adding the library is not mandatory. In this case the login process will be initiated via Chrome using Intent.ACTION_VIEW.

 

Provider Selection Screen

You can show a dialog with defined social providers in the following way:

 

Java

/*
Define the list of providers your application supports.
*/
final List<String> providers = new ArrayList<>();
providers.add(FACEBOOK);
providers.add(GOOGLE);
providers.add(LINE);
 
/*
Show providers selection UI
*/
mGigya.socialLoginWith(providers, null, new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

Here is a screenshot using the above implementation:

 

Login With A Specified Provider

Alternatively, you can initiate social login flow to a specific social provider:

 

Java

/*
Sign in with Facebook.
*/ 
mGigya.login(FACEBOOK, new HashMap<>(), new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

Configuring Native Login

For some social providers, the SDK supports social login via the social provider's native implementation. 
It is done by using the provider's native SDK, so it will require you to add its required libraries as dependencies to your Android project.

We will review the relevant providers and their implementation flow.

Facebook

Adding Facebook native login to your Android app is mandatory if you want to login via Facebook. To do so, set up your Facebook app in your Android Studio project using the following instructions:

If you do not yet have an active Facebook app please see our Facebook documentation.

For mobile specific. please go to Facebook Mobile App Setup.

Setting up the Facebook dependency:

Add the following line to your application's build.gradle file. 

The current tested Facebook api version is 4.41.0.

implementation 'com.facebook.android:facebook-android-sdk:4.41.0'

Add the following lines to your AndroidManifest.xml file. It is recommended that the facebook_app_id String be placed in the your res/values/strings.xml file.

<activity
    android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    tools:replace="android:theme" />
 
<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_app_id" />

 

Google

Android enables users to set their Google account on their device. Using Google Sign-In is mandatory if you want users to login via Google.

Instructions for adding Google Sign-in to your Android device can be found at Google Sign-In for Android.

Add the following line to your application's build.gradle file. 

The current tested Google auth api version is 16.0.1.

implementation 'com.google.android.gms:play-services-auth:16.0.1'

Add the following meta-data tag to your  AndroidManifest.xml  file.  It is recommended that the google_client_id String be placed in the your res/values/strings.xml file.

Note that the required client_id is the Web client id generated when you create your Google project. This should not be mistaken with the Android OAuth client id. Make sure that your Google project contains both.

<meta-data
    android:name="googleClientId"
    android:value="@string/google_client_id" />

Although Google Sign-in is not available via WebView anymore, it is not mandatory to add the Google auth library dependency. If not added, the SDK will use Intent.ACTION_VIEW and execute the sign in process via Chrome.

 

LINE

The Gigya Android SDK allows you to enable LINE native login for users that have the LINE app installed.

Instructions for adding LINE Native Login to your Android device can be found at Integrating LINE Login with an Android app.

The GIgya SDK currently supports LINE SDK v4 for Android.

Download the line SDK from the LINE Download website. The current tested LINE login api version is 4.0.10.

Add the downloaded .AAR file to your /libs folder of your Android application.

Make sure you have the following in your application's build.gradle file.

implementation files('libs/line-sdk-4.0.10.aar')

You must generate a package signature to place in your LINE Channels > Technical configuration > Android Package Signature field. 

The signature you need is the SHA1 signature, you can generate it according to the following:

// Code to generate Package Signature
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
   
//Returns -> SHA1: DD:D3:1B:4.....xxxxx.....
//Convert To -> DDD31B4xxxxxxx.............xxxxxx

Once you have the signature, remove the colons (":") and then paste it to the respective field in LINE's Developers Console.

Add the following to your  AndroidManifest.xml It is recommended that the line_Channel_ID String be placed in the your res/values/strings.xml file

<meta-data
    android:name="lineChannelID"
    android:value="@string/line_Channel_ID" />

 

WeChat

The Gigya Android SDK allows you to enable WeChat native login for users that have the WeChat app installed.

Add the following the dependency to your application's build.gradle file.

The current tested WeChat api version is 5.3.1.

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:5.3.1'

The the following to your AndroidManifest.xml.   It is recommended that the wechatAppID String be placed in the your res/values/strings.xml file.

<activity
    android:name=".wxapi.WXEntryActivity"
    android:exported="true"
    android:label="@string/app_name"
    android:launchMode="singleTop" />
 
<meta-data
    android:name="wechatAppID"
    android:value="@string/wechatAppID" />

Create a sub folder in the root of your project called wxapi. In that folder, create an activity named WXEntryActivity which must contain the following:

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WeChatProvider.handleIntent(this, getIntent(), this);
        finish();
    }
 
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        WeChatProvider.handleIntent(this, getIntent(), this);
        finish();
    }
 
    @Override
    public void onReq(BaseReq baseReq) {
        // Stub. Currently unused.
    }
 
    @Override
    public void onResp(BaseResp baseResp) {
        WeChatProvider.onResponse(baseResp);
    }
 
    @Override
    public void finish() {
        super.finish();
        // Disable exit animation.
        overridePendingTransition(0, 0);
    }
}

Once you've tested your app, run the signature generation tool available from WeChat at https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319167&token=&lang=en_US.

Use the tool to generate the app signature and update your setting in the WeChat console.

Important Notes

  • The signature generation tool must be installed on the mobile device.
  • You will not be able to test WeChat functionality using an emulator. WeChat requires a physical mobile device.
  • Once you update your app signature in the WeChat console, it could take a couple of hours to update.
  • If you experience problems and notice errCode -6 from WeChat while debugging, it means the signature isn't correct.

 

Logout

A simple logout is available by using:

mGigya.logout();

Logging out will clear all session data from the device.

 

Account Handling

The SDK provides various account handling interfaces to simplify fetching and updating the user's data.

Providing A Custom Account Schema

In your Gigya implementation you have probably extended the default Account Schema according to your business requirements:

 

Gigya's Android SDK allows you to get a smooth developing experience by binding the SDK's main Gigya instance to a class of the same structure as your schema.

This will allow the SDK to accept and return account instances according to your specification.

Here is an example of a custom Account Schema class, which corresponds with the above site's Schema.

 

Java

public class MyAccount extends GigyaAccount {
 
    private MyData data;
 
    public MyData getData() {
        return data;
    }
 
    private static class MyData {
 
        private String comment;
        private Boolean subscribe;
        private Boolean terms;
 
        public String getComment() {
            return comment;
        }
 
        public Boolean getSubscribe() {
            return subscribe;
        }
 
        public Boolean getTerms() {
            return terms;
        }
    }
}

We can initialize a Gigya instance with the MyAccount class, and see the account methods operate accordingly.

Get Account

In order to retrieve the current account you can use the getAccount method:

 

Java

mGigya.getAccount(new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount account) {
        // Success
        System.out.println(account.terms);
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

Using getAccount requires you to have a valid session.

In order to improve the end-user's experience by avoiding unnecessary network requests, the SDK caches the current account data for a period of 5 minutes (by default).

The account cache property can be set via the JSON configuration file or by adding a meta-data tag as show in the initializationsection of the document.

To bypass the account's caching:

Provide true when requesting a new account.

Java

mGigya.getAccount(true, new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

Set Account

The SDK provides two options for updating a user account data.

Using setAccount requires  you to have a valid session.

In order to avoid unnecessary errors, please make sure that the fields you trying to update are marked as userModify in the site's schema.

You can verify this using Gigya's Admin Console, in your site's Schema Editor page under the Settings panel.

Case 1, Update the account using the setAccount method providing an updated account object.

 

Java

/*
Using live data to keep track of account object changes.
*/
mGigya.setAccount(myAccountLiveData.getValue(), new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
   
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

 

Case 2, Update the account using the setAccount method. Providing the update parameters requested.

As stated in the  setAccountInfo  REST preferences, complex objects should be serialized into JSON format.

Java

/*
Creating a map of requested update fields
*/
final Map<String, Object> profile = new HashMap<>();
profile.put("age", 25);
profile.put("firstName", "John");
   
/*
Adding profile object to updated parameters. Using GSON to format the data before sending.
*/
final Map<String, Object> params = new HashMap<>();
params.put("profile", new Gson().toJson(profile));
   
mGigya.setAccount(params, new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
   
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

 

Using Screen-Sets

Screen-Sets, as one of Gigya's most powerful features, are available also in your mobile app!

The SDK provides a simple interface for using & displaying screen-sets via the PluginFragment and the GigyaPluginCallback components.

ShowScreenSets method

Using screen-sets is available using the "showScreenSet" method of the Gigya interface.

Here is an example of using the SDK's showScreenSet method using the default "Registration-Login" screen set.

Java

/*
Showing "Registration-Login" screen set in a dialog mode. Overriding only the onLogin method to be notified when logging in event was fired.
*/
mGigya.showScreenSets("Default-RegistrationLogin", false, null, new GigyaPluginCallback<MyAccount>() {
   
    @Override
    public void onLogin(@NonNull MyAccount accountObj) {
       // Login success.
    }
});

The showScreenSets method available parameters include:

  • All parameters that the web screen-sets plugin can receive.
  • Optional Boolean fullScreen field which will force the displaying of the PluginFragment to fit into the screen.

Customizing the look & feel of the PluginFragment is recommended.

It can be done by simply copying the gigya_plugin_fragment.xml file from the SDKs source code to your application res/layout folder directory.

Once copied you will be able to change & customize the layout to your choosing (with some restrictions of course).

Keep in mind that you cannot remove any element or change any existing element id . Doing so could result in unexpected crashes, as the SDK will still expect these elements to be presented.

GigyaPluginCallback Class

This callback class is an abstract class which is aligned to all optional plugin events fired by the screen-sets plugin. In addition, convenience methods, such as onLogin and onLogout, are also available for override.

Here is the callback to its extent. Overriding all methods is optional.

final GigyaPluginCallback<MyAccount> pluginCallback = new GigyaPluginCallback<MyAccount>() {
     
    @Override
    public void onError(GigyaPluginEvent event) {
        super.onError(event);
    }
 
    @Override
    public void onBeforeValidation(@NonNull GigyaPluginEvent event) {
        super.onBeforeValidation(event);
    }
 
    @Override
    public void onBeforeSubmit(@NonNull GigyaPluginEvent event) {
        super.onBeforeSubmit(event);
    }
 
    @Override
    public void onSubmit(@NonNull GigyaPluginEvent event) {
        super.onSubmit(event);
    }
 
    @Override
    public void onAfterSubmit(@NonNull GigyaPluginEvent event) {
        super.onAfterSubmit(event);
    }
 
    @Override
    public void onBeforeScreenLoad(@NonNull GigyaPluginEvent event) {
        super.onBeforeScreenLoad(event);
    }
 
    @Override
    public void onAfterScreenLoad(@NonNull GigyaPluginEvent event) {
        super.onAfterScreenLoad(event);
    }
 
    @Override
    public void onFieldChanged(@NonNull GigyaPluginEvent event) {
        super.onFieldChanged(event);
    }
 
    @Override
    public void onHide(@NonNull GigyaPluginEvent event, String reason) {
        super.onHide(event, reason);
    }
 
    @Override
    public void onLogin(@NonNull MyAccount accountObj) {
        super.onLogin(accountObj);
    }
 
    @Override
    public void onLogout() {
        super.onLogout();
    }
 
    @Override
    public void onConnectionAdded() {
        super.onConnectionAdded();
    }
 
    @Override
    public void onConnectionRemoved() {
        super.onConnectionRemoved();
    }
};

The plugin callback is also typed to the current Account schema.

 

Business APIs

The Gigya SDK provides popular built-in flows for fluent development.

Currently available:

  • login
  • register
  • logout
  • verifyLogin
  • getAccount
  • setAccount
  • forgotPassword
  • addConnection
  • removeConnection

 

Business APIs are provided in order to give you an easier interface. If a more detailed and customized use is required, you can still use the generic Gigya.send interface for all request purposes.

 

Interruptions

Some flows can be "interrupted" due to certain Site policies.
For example, when trying to register but Two Factor Authentication is required - then an "interruption" can occur about "pending TFA registration" that will require the end user to setup a TFA method before being able to complete the registration flow.

Interruptions map:

 

The SDK's Business APIs are design to help to easily develop a friendly way to face and resolve those interruptions in order to get the end user logged in and still complying to the site's policies.

Handling Interruptions

Interruption handling is a key feature introduced as of the Android SDK v4.

The SDK will expose a resolver object for supported interruptions in order to give you as a developer the ability to resolve them within the same flow that they were triggered.

The current supported interruption flows are:

  • Account linking
  • TFA registration
  • TFA verification

 

All interruption flows are implemented in the provided Sample project.

Interruptions handling - Account linking example

We will start with a simple register request for an email address that is already regisered:

mGigya.register("EMAIL-ADDRESS-ALREADY-REGISTERED", "PASSWORD", new GigyaLoginCallback<MyAccount>() {
 
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
});

As expected we will receive an error which indicates that this login identifier already exists in the system (errorCode 403043).

Usually when receiving that kind of error, we would trigger an API call to retrieve the conflicting accounts (via  accounts.getConflictingAccount ), then try to login with one of the supported account's identities (using  mode:"link" ).

Luckily, the SDK can handle this interruption for us:

To do so, in our our GigyaLoginCallback we will override the onConflictingAccounts method:

mGigya.register("EMAIL-ID-ALREADY-REGISTERED", "PASSWORD", new GigyaLoginCallback<MyAccount>() {
 
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
        // Fail
    }
 
    @Override
    public void onConflictingAccounts(@NonNull GigyaApiResponse response, @NonNull GigyaLinkAccountsResolver resolver) {
         
    }
});

While the response parameter contains the original response from the register API call (accounts.register), the resolver object (of type GigyaLinkAccountsResolver) already contains all we need in order to complete the flow:

We can get the conflicting accounts from it and try to link the account to them.

final ConflictingAccounts accounts = resolver.getConflictingAccounts();
final List<String> providers = accounts.getLoginProviders();
final String loginID = accounts.getLoginID();
  
/*
In this example the providers list contains one "site" provider. Therefore we are now able to try and resolve the flow.
*/ 
resolver.linkToSite(loginID, "PASSWORD-REQUIRED-TO-VERIFY-THE-ORIGINAL-ACCOUNT");

Trying the resolve the flow will now try to login with the original conflicted account and link both accounts. 

If the operation was successful, the original GigyaLoginCallback will be notified and the flow will be directed to its original onSuccess method.

In order to provide the end user with a fluid experience some UI intervention is recommended. Example for this can be found in the Sample application.

 

Session Features

Handling Fixed Session Expiration

Starting a new session via register or login is also available with a fixed time span expiration constraint.

For example:

 

Java

/*
Adding a 10 minutes session expiration constraint.
*/
final Map<String, Object> params = new HashMap<>();
params.put("sessionExpiration", 10);
 
mGigya.register("EMAIL", "PASSWORD", params, new GigyaLoginCallback<MyAccount>() {
    @Override
    public void onSuccess(MyAccount obj) {
        // Success
    }
 
    @Override
    public void onError(GigyaError error) {
         // Fail
    }
});

When the session expires, the SDK will notify about it via broadcast.

In order to be notified of session changes, you will need to register a broadcast receiver in your Activity, for example:

 

Java

final BroadcastReceiver sessionLifecycleReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
         final String action = intent.getAction();
         if (action == null) {
             return;
         }
         String message;
         switch (action) {
             case GigyaDefinitions.Broadcasts.INTENT_ACTION_SESSION_EXPIRED:
                 message = "Your session has expired";
                 break;
             case GigyaDefinitions.Broadcasts.INTENT_ACTION_SESSION_INVALID:
                 message = "Your session is invalid";
                 break;
         }
    }
};
  
@Override
protected void onResume() {
    super.onResume();
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(GigyaDefinitions.Broadcasts.INTENT_ACTION_SESSION_EXPIRED);
    intentFilter.addAction(GigyaDefinitions.Broadcasts.INTENT_ACTION_SESSION_INVALID);
    LocalBroadcastManager.getInstance(this).registerReceiver(sessionLifecycleReceiver, filter);
}
 
@Override
protected void onPause() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(sessionLifecycleReceiver);
    super.onPause();
}

For session expiration updates use INTENT_ACTION_SESSION_EXPIRED action.

 

Verify Login Interval - Session validation

The Android SDK can track a user's current session and determine if there were changes to the API schema and require re-authentication for him when necessary. 

For example, this can be used to invalidate a user's session if the version of their agreed terms of use consent has changed.

When using session verification, the client application will be informed, via local broadcast, if the automatic verification fails. This will allow your application to perform the necessary logic in order to re-authenticate the user.

Updating the AndroidManidest.xml file:

<meta-data
    android:name="sessionVerificationInterval"
    android:value=60 />  // The verification call interval in seconds.

Adding this meta-data tag will cause the SDK to perform a periodic session validation according to provided value (in seconds).

When a session changes state, the verification call will fail and the SDK will invalidate the current session and broadcast an event locally.

Session validation calls will only occur while the application is in the foreground.

 

Using the GigyaWebBridge explicitly.

You are able to use the GigyaWebBridge.java class explicitly in order to attach Gigya's web sdk actions into your own WebView implementation. Attaching the GigyaWebBridge will allow you to add Gigya's session management you your custom web implementation. Special cases include uses of SAML & captcha implementations. The following snippet demonstrates the basic implementation of the GigyaWebBridge.

private var _webBridge: IGigyaWebBridge<MyAccount>? = null
  
/*
Make sure you enable javascript for your WebView instance.
*/
val webSettings = web_view.settings
webSettings.javaScriptEnabled = true
  
/*
Generate a new GigyaWebBridge instance.
*/
_webBridge = Gigya.getInstance(MyAccount::class.java).createWebBridge()
 
 
/*
Attach newly create GigyaWebBridge to WebView instance.
*/
_webBridge?.attachTo(web_view, object: GigyaPluginCallback<MyAccount>() {
  
    // Implement any optional callback you require.
     
    override fun onLogin(accountObj: MyAccount) {
        // Logged in.
    }
  
}, progress_indicator /* Optional progress indicator view to be displayed on loading events */)
  
/*
Make sure to attach the GigyaWebBridge to your WebViewClient instance.
*/
web_view.webViewClient = (object: WebViewClient() {
  
    override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
    val uri = request?.url
    val uriString = uri.toString()
    return _webBridge?.invoke(uriString) ?: false
    }
})

It is recommended that you also detach the GigyaWebBridge from your WebView instance.

Make sure you implement it in the appropriate lifecycle callback.

_webBridge?.detachFrom(web_view)

 

Biometric Authentication

End User & Biometric Authentication

The biometric fingerprint feature is a security encryption on top of an existing session of your app, therefore, calling any biometric operations requires a valid session.

The supported end user flow for the biometric authentication feature is:

  • End user logs in
  • End user opts in to biometric authentication
    • This will require the end user to verify his fingerprint
  • The app is locked or being cleared from memory
  • End user is required to unlock the app in order to restore his session
    • This will require the end user to verify his fingerprint
  • End user opts out of biometric authentication

Biometric fingerprint support is available for devices running Android Marshmallow and above.

In order to add fingerprint authentication to your application you will need to include the Gigya Biometric library in your application's dependencies.

Download the biometric library and copy it to your applications libs/ folder.

Then add the following line to your application's build.gradle file:

implementation files('libs/Gigya-android-biometric-1.0.1.aar')
  
// In addition you will need to add this dependency as well.
implementation 'com.android.support.design:28.0.0'

Relevant permissions are already requested in the library manifest.

  • android.permission.USE_FINGERPRINT
  • android.permission.USE_BIOMETRIC

The Android SDK v4 differs from the previous releases in the way that is handles the UI prompt for you. 

It Utilizes Google's biometric prompt class on Android devices running Android Pie (and above).  

On Android devices that run any other version below Pie (M, N, O) - a custom prompt will be shown.

It is not longer possible to customize the biometric prompt.

Authentication flow

In order to use biometric fingerprint authentication, several rules must apply:

  1. The device has a fingerprint sensor available.
  2. A minimum of 1 fingerprint already enrolled in the device.

If one of the above rules isn't satisfied, the biometric feature availability will return false.

GigyaBiometric biometric = GigyaBiometric.getInstance();
final boolean available = biometric.isAvailable(); // WILL BE false.

Available authentication methods:

  • Opt-In - Opts-in the existing session to use fingerprint authentication.
  • Opt-Out - Opts-out the existing session from using fingerprint authentication.
  • Lock - Locks the existing session until unlocking it. No authentication based actions can be done while the session is locked.
  • Unlock - Unlocks the session so the user can continue to make authentication based actions.

 

Example of fingerprint authentication flow:

 

Java

/*
Reference biometric interface.
*/
final GigyaBiometric biometric = GigyaBiometric.getInstance();
if (!biometric.isAvailable()) {
    return;
}
 
/*
Generate a prompt info class
*/
final GigyaPromptInfo info = new GigyaPromptInfo(
        "PROMPT-TITLE",
        "PROMPT-SUBTITLE",
        "PROMPT-DESCRIPTION-OPTIONAL"
);
 
/*
Use authentication action
*/
biometric.optIn(this, info, new IGigyaBiometricCallback() {
    @Override
    public void onBiometricOperationSuccess(@NonNull GigyaBiometric.Action action) {
        // Action success.
    }
 
    @Override
    public void onBiometricOperationFailed(String reason) {
        // Action failed with provided reason.
    }
 
    @Override
    public void onBiometricOperationCanceled() {
        // Action canceled by user.
    }
});

 

GigyaPromptInfo Class

A helper class used for adding biometric prompt display data.

IGigyaBiometricCallback Interface class

Biometric authentication action callback that provides the result interface given a biometric prompt action.

final IGigyaBiometricCallback biometricCallback = new IGigyaBiometricCallback() {
    @Override
    public void onBiometricOperationSuccess(@NonNull GigyaBiometric.Action action) {
        // Action success. Available actions are OPT_IN, OPT_OUT, LOCK, UNLOCK.
    }
 
    @Override
    public void onBiometricOperationFailed(String reason) {
        // Action failed with provided reason.
    }
 
    @Override
    public void onBiometricOperationCanceled() {
        // Action canceled by user.
    }
};

 

FAQ

General

 What is the minimum SDK supported by Gigya's Android SDK (v4)?

Gigya Android SDK requires SDK 14 and above.

Gigya Android Biometric requires SDK 23 and above.

 Is Gigya's Android SDK v4 compatible with older version releases?

Upgrading application from v3 to v4 is supported. Migration of your application code is required.

Biometric

 Is the fingerprint saved in the application?

No. Gigya's Android SDK uses the device's enrolled fingerprint.

 Can I use fingerprint authentication before the user logs in?

No. Fingerprint authentication acts as an additional layer of security that can be added in addition to the current existing session encryption.

 Do I need to develop a custom UI for the fingerprint authentication flow?

No. Biometric prompt is provided for you for all supported operating systems.

 

Caveats

Android WebView

Be advised that the Gigya Android SDK asynchronous nature uses timers to achieve different functionality for a smooth user experience, specifically for Web plugins such as Screen-Sets. This means that if your application is using WebViews you should avoid calling pauseTimers(), as this will cause erratic and inconsistent behaviour of the SDKs functions. If you ever do need to call pauseTimers(), be sure to call resumeTimers() prior to any further interaction of the Gigya SDK.

Note that calling pauseTimers()/resumeTimers() is a global request and is not restricted to any specific instance.  For more information see, https://developer.android.com/reference/android/webkit/WebView#pauseTimers().

 

  • No labels