This guide details how to integrate Mobile Connect into your Android apps using the Mobile Connect SDK for Android. It is strongly recommended that you read through this guide and familiarise yourself with the functions the SDK provides before downloading an demo app and starting to code.

The guide describes the processes for:

Prerequisites

Before you can make calls to Mobile Connect, you must have registered for a Mobile Connect user account and registered an application. This will provide you with your developer credentials, which you will need to specify in a configuration object, and your Application Short Name, which is a required parameter when calling the Authorisation or Identity endpoints.

Configuring your Project

  1. Download the Mobile Connect SDK.

    1. From a command line, run the following:

      git clone https://github.com/Mobile-Connect/android_sdk_v3
    2. Open both the DemoApp project and the sdk projects in Android Studio.

    3. Download and install any missing dependencies or plugins from the links displayed in the console output.

      Android Studio messages screenshot

  2. Add the following permission to Mobile App's AndroidManifest.xml file::
    no errors

    <uses-permission android:name="android.permission.INTERNET"/>

Using the SDK with Mobile Connect

The Mobile Connect SDK for Android automates much of the basic housekeeping and configuration tasks of your application’s integration with Mobile Connect. Many of these functions activate in the Discovery phase, independently of the Identity Gateway endpoint your application will ultimately call, and so are described here for your reference.

Provider Metadata

A successful call to the Mobile Connect Discovery endpoint returns the end user’s Mobile Network Operator (MNO) and describes the Mobile Connect services that MNO supports, via a URI to the MNO’s Provider Metadata. The metadata describes the Identity Gateway endpoints (Mobile Connect services) your application or service can use and how those endpoints are configured – for example, the response types an endpoint can return, the subject identifier types supported, or the Identity Services encryption algorithms in use.

Although Provider Metadata is the primary source of information detailing the Identity Gateway configuration, it does not change often, so a cached version can be used without risk of expired data causing errors. The Mobile Connect SDK handles both the querying of the Provider Metadata and the caching.

  • If the Provider Metadata URI returns no data, the cached metadata is used.
  • Where the cached data is out of date (defaulting to 15-minute intervals) a subsequent query of the URI is attempted, and in the event of a second failed response, expired cached data is used.
  • Should neither the cached data nor the Provider Metadata URI return data (such as an error upon first user login) default values are used.

Regardless of the source, the SDK parses the Provider Metadata into a discrete list of properties. See the OpenID Provider Metadata definition for a list of the metadata available, although you should note that Mobile Connect's implementation may not be exhaustive.

The ProviderMetadata object is available on DiscoveryResponse.ProviderMetadata.

Back to top

Supported Services

Before your application or service can call an Identity Gateway endpoint (scope), you need to know if the MNO supports the scope you are calling. The Mobile Connect SDK provides the method isMobileConnectServiceSupported(String scope) in the discoveryReponse, which can be accessed as follows:

bool supported = discoveryResponse.IsMobileConnectServiceSupported(“mc_authz mc_identity_signup”)

The method accepts a comma- or space-separated list of scopes, which it then checks against the list of supported scopes in the Provider Metadata.

  • If all of the scopes passed as arguments are present in the Provider Metadata, the function returns true.
  • If any of the passed scopes are not present in the metadata, the function returns false.
  • If the Provider Metadata is not available, or the scopes attribute is missing, null, or an empty string, the function returns an exception: “Provider Metadata scopes unavailable”.

Back to top

Version Compatibility

Although the MNOs may support differing versions of the Mobile Connect APIs, the SDK automatically detects the version in use at an Identity Gateway from the Provider Metadata, and ensures that the correct Mobile Connect Profile is used when making calls to the Mobile Connect APIs.

Back to top

Application Short Name

The application you register with the Mobile Connect Developer Portal includes an Application Short Name, which is stored in the API Exchange and returned in responses from the Discovery service. The SDK captures the returned applicationShortName and includes it when constructing calls to the Mobile Connect Authorisation and Identity endpoints. Following a successful call, the Application Short Name is displayed to the end user to identify the application requesting either authorisation for a transaction or permission to share their user information.

Back to top

Mobile Connect Constants

The SDK provides a number of constants for referencing the Mobile Connect services by scope. They are available at com.gsma.mobileconnect.r2.constants.Scopes, and can be called using the following syntax:

com.gsma.mobileconnect.r2.constants.Scopes.MOBILECONNECTIDENTITYPHONE

The above example calls the scope "openid mc_identity_phonenumber". You can pass multiple scopes as a space-separated string; the SDK will remove any duplicates before making the call to the Identity Gateway.

The following constants are available:

Mobile Connect Product Constant Identifier Literal Value
Authentication (v1.0) MOBILECONNECT "openid"
Authentication (v1.1) MOBILECONNECTAUTHENTICATION "openid mc_authn"
Authorisation MOBILECONNECTAUTHORIZATION "openid mc_authz"
Identity: Phone Number MOBILECONNECTIDENTITYPHONE "openid mc_identity_phonenumber"
Identity: Signup MOBILECONNECTIDENTITYSIGNUP "openid mc_identity_signup"
Identity: Signup Plus* MOBILECONNECTR3IDENTITYSIGNUPPLUS "openid mc_identity_signupplus"
Identity: National ID MOBILECONNECTIDENTITYNATIONALID "openid mc_identity_nationalid"

*This constant is available to support possible future products.

Back to top

Login Hint Support

You have the option to provide the login hint to the Identity Gateway in one of three formats: MSISDN, encrypted MSISDN, and PCR. Your decision on how to provide the login hint is governed by two factors:

  • The login hint formats supported by the Identity Gateway.
  • Whether you are a “Trusted Service Provider”; an unencrypted MSISDN is only accepted from a trusted provider – attempting to send one if you are not trusted returns an error.

The Mobile Connect SDK provides functions to test for login hint support in the Identity Gateway, namely:

  • isLoginHintMSISDNSupported
  • isLoginHintEncryptedMSISDNSupported
  • isLoginHintPCRSupported

Each function checks the login_hint_methods_supported attribute in the Provider Metadata returned from the Discovery endpoint. Should the attribute be missing, the function checks the Mobile Connect Profile version supported; only version 1.2 supports passing the PCR as the login hint.

Once you have decided how to provide the login hint, the SDK offers a further three functions to build it for you:

  • generateLoginHintMSISDN(String MSISDN)
  • generateLoginHintEncryptedMSISDN(String encryptedMSISDN)
  • generateLoginHintPCR(String PCR)

Back to top

id_token Validation

A successful response from the Identity Gateway includes an id_token – a JSON Web Token, which validates against a JSON Web Keyset (JWKS), available at a URL specified in the Provider Metadata attribute jwks_uri.

The SDK performs a number of automatic validation actions to ensure the integrity of the response source, such as checking whether the token has expired. It also fetches the data from the jwks_uri location and stores it alongside the associated Discovery response, where it is cached. The following functions are then available to you to support id_token validation:

  • checkIDTokenSignature(id_token) verifies the signature of the id_token based on the jwks_uri data. A successful validation returns true; a failed validation returns false; a missing JWKS certificate returns an error.
  • returnAllJWKSEntries allows you to fetch all of the keys from the JWKS data.
  • returnMatchingJWKSEntries allows you to fetch specific keys matching the following parameters:

    • kty – key type (e.g. RSA)
    • alg – algorithm (e.g. RS256)
    • use – sig (signature) or enc (encryption)
    • kid – key identifier

Back to top

Using Mobile Connect Authentication

The SDK allows you to call a method that accepts a reference to a configuration file as a parameter. With your developer credentials specified in the configuration file, you have everything you need to make a successful call to the Mobile Connect Discovery endpoint, and the methods attemptDiscovery(), startAuthentication(), and handleUrlRedirect do just that, building and making the call, and then handling the response. The SDK also takes care of caching the response for re-use in a subsequent call – subject to the configured timeout. Once the end user has entered their MSISDN or specified their operator, and a successful Discovery response is received, the SDK builds the call to the Authentication endpoint. A successful authentication returns an id_token containing the user’s PCR, which is unpacked and available for verification against your user register.

  1. In Android Studio, create a new Activity, named MainActivity.
  2. In MainActivity create an instance of MobileConnectAndroidView as mentioned earlier at class level (a field).

  3. Create an instance of the MobileConnectConfig class and set the attributes based on your Mobile Connect application credentials.

    Note: if you operate in the EU then you should use EU Discovery Service domain: eu.discover.mobileconnect.io

    new MobileConnectConfig.Builder()
                .withClientId("<yourClientId>")
                .withClientSecret("<yourClientSecret>")
                .withDiscoveryUrl("<yourDiscoveryUrl>")
                .withRedirectUrl("<yourRedirectUrl>")
                .build();
  4. Instantiate the MobileConnectAndroidView class and pass it the configuration MobileConnectConfig.

    Note: MobileConnectAndroidView is part of the Mobile Connect SDK for Android. It wraps the Mobile Connect Discovery, Authentication, and Identity services into a single class that can be called with the minimum parameters.

    The Android SDK can be interfaced with via the MobileConnectAndroidView. First, an instance of this class is required which takes the following a MobileConnectInterface object.

    MobileConnect mobileConnect = new MobileConnect.Builder(mobileConnectConfig, new AndroidMobileConnectEncodeDecoder()).build();
    
    MobileConnectInterface mobileConnectInterface = mobileConnect.getMobileConnectInterface();
    
    mobileConnectAndroidView = new MobileConnectAndroidView(mobileConnectInterface);

    Calling mobileConnectAndroidView.initialise(); and mobileConnectAndroidView.cleanUp(); is necessary from the Activity/Fragment’s onStart/onStop.

  5. Add a method startDiscovery() to call the Mobile Connect Discovery service.

    mobileConnectAndroidView.attemptDiscovery(msisdn, mcc, mnc, requestOptions, iMobileConnectCallback);

    Once the user completes their interaction with the target page, the client is redirected.

  6. The iMobileConnectCallback parameter will capture the redirect containing the results of calls to both the Discovery and Identity Gateway endpoints. The client must forward then perform the necessary action based on the result:

    protected void handleRedirect(final MobileConnectStatus mobileConnectStatus)
    {
        final String state =
                mobileConnectStatus.getState() == null ? UUID.randomUUID().toString() : mobileConnectStatus.getState();
        final String nonce =
                mobileConnectStatus.getNonce() == null ? UUID.randomUUID().toString() : mobileConnectStatus.getNonce();
    
        switch (mobileConnectStatus.getResponseType())
        {
            case ERROR:
            {
                Toast.makeText(getActivity(),
                               String.format("Error - %s", mobileConnectStatus.getErrorMessage()),
                               Toast.LENGTH_LONG).show();
                break;
            }
            case OPERATOR_SELECTION:
            {
                mobileConnectAndroidView.attemptDiscoveryWithWebView(getActivity(),
                                                                     this,
                                                                     mobileConnectStatus.getUrl(),
                                                                     mobileConnectConfig.getRedirectUrl().toString(),
                                                                     null);
                break;
            }
            case START_AUTHENTICATION:
            {
                AuthenticationOptions.Builder authenticationOptionsBuilder = new AuthenticationOptions.Builder().withScope(Scopes.MOBILECONNECTAUTHENTICATION);
    
                final MobileConnectRequestOptions.Builder mobileConnectRequestOptionsBuilder = new
                        MobileConnectRequestOptions.Builder();
    
    
                final MobileConnectRequestOptions mobileConnectRequestOptions = mobileConnectRequestOptionsBuilder
                        .withAuthenticationOptions(
                        authenticationOptionsBuilder.build()).build();
    
                mobileConnectAndroidView.startAuthentication(mobileConnectStatus.getDiscoveryResponse()
                                                                                .getResponseData()
                                                                                .getSubscriberId(),
                                                             state,
                                                             nonce,
                                                             mobileConnectRequestOptions,
                                                             new IMobileConnectContract.IMobileConnectCallback()
                                                             {
                                                                 @Override
                                                                 public void onComplete(final MobileConnectStatus
                                                                                                mobileConnectStatus)
                                                                 {
                                                                     handleRedirect(mobileConnectStatus);
                                                                 }
                                                             });
                break;
            }
            case AUTHENTICATION:
            {
                mobileConnectAndroidView.attemptAuthenticationWithWebView(getActivity(),
                                                                          this,
                                                                          mobileConnectStatus.getUrl(),
                                                                          state,
                                                                          nonce,
                                                                          null);
                break;
            }
            case COMPLETE:
            {
                showTokens(mobileConnectStatus);
                break;
            }
        }
    }

    This covers all possibilities and uses one central logic to handle all scenarios. The call to Authentication is within the START_AUTHENTICATION branch within the switch statement.

    AuthenticationOptions.Builder authenticationOptionsBuilder = new AuthenticationOptions.Builder().withScope(Scopes.MOBILECONNECTAUTHENTICATION);
    
                final MobileConnectRequestOptions.Builder mobileConnectRequestOptionsBuilder = new
                        MobileConnectRequestOptions.Builder();
    
    
                final MobileConnectRequestOptions mobileConnectRequestOptions = mobileConnectRequestOptionsBuilder
                        .withAuthenticationOptions(
                        authenticationOptionsBuilder.build()).build();
    
                mobileConnectAndroidView.startAuthentication(mobileConnectStatus.getDiscoveryResponse()
                                                                                .getResponseData()
                                                                                .getSubscriberId(),
                                                             state,
                                                             nonce,
                                                             mobileConnectRequestOptions,
                                                             new IMobileConnectContract.IMobileConnectCallback()
                                                             {
                                                                 @Override
                                                                 public void onComplete(final MobileConnectStatus
                                                                                                mobileConnectStatus)
                                                                 {
                                                                     handleRedirect(mobileConnectStatus);
                                                                 }
                                                             });

    Note: the first two null parameters correspond to state and nonce in the startAuthentication method of mobileConnectAndroidView. You can pass strings generated using your own methods or leave them null, in which case startAuthentication generates values for you. The last null value corresponds to the options parameter, which enables the passing of a scope for Authorisation and ID & Attributes services; where no scope is passed, the requested service defaults to Authentication.

    A successful call returns a URL, to which the client must be navigated. Once the user completes their interaction with the target page, the client is redirected. The client must forward the redirected URL’s parameters, as appropriate, using a GET action to the redirect handler route. This results in a final response from the Identity Gateway containing the id_token.

Back to top

Using Mobile Connect Authorisation

The SDK allows you to call the Identity Gateway with the scope parameter set to “mc_authz”, which signifies an authorisation request for a single transaction (the id_token and access token returned from the Gateway have a timeout set to zero, so expire after a single use). You should check that the Identity Gateway supports version 1.2 of the Mobile Connect Profile (available in the Provider Metadata) before attempting a call, but note that the SDK sets the version to “mc_v1.2” automatically.

To make a successful authorisation call, you must provide the following additional parameters:

  • client_name – specifies the name of the application/service requesting authorisation. This must match the Application Short Name returned by the Discovery service. If no client_name is specified, the SDK will handle this for you.
  • context – specifies the reason for the authorisation request, and should be built from the data describing the transaction requiring authorisation. The context is displayed on the authenticating (mobile) device only.
  • binding_message – specifies a reference string to display on the device from which the authorisation request was invoked, and on the authenticating (mobile) device, allowing the user to visually verify that the confirmation message originated from their transaction request.

Note: the authorisation prompt displayed to the user combines all three parameters, which cannot exceed 93 bytes in total.

To finally perform Authorisation, the exact same code can be used for Authentication except using a different scope value for the AuthenticationOptions :

AuthenticationOptions.Builder authenticationOptionsBuilder = new AuthenticationOptions.Builder().withScope(Scopes.MOBILECONNECTAUTHORIZATION);

The level of authentication required to authorise the transaction defaults to LoA2 (Authorisation), but you can increase it by adding the optional parameter “acr_value” and setting the value to 3 (for Authorisation Plus).

Back to top

Using Mobile Connect Identity and Attributes

A successful call to the Authorisation endpoint returns an id_token identifying the user, and an access token that grants your application permission to request their personal information (referred to as Claims). This information contains a range of data; the exact data you can request is specified in the access token, and is limited to those Claims the end user has permitted as part of the original authorisation request.

Note: the access token is for single use only, and expires immediately upon use.

You request access to the Identity endpoint by specifying the appropriate scope. The SDK provides constants that you can pass when requesting specific Identity products:

  • Identity: Phone Number – MOBILECONNECTIDENTITYPHONE
  • Identity: Sign-up – MOBILECONNECTIDENTITYSIGNUP
  • Identity: National Identity – MOBILECONNECTIDENTITYNATIONALID

Upon successful authorisation, the SDK provides an IdentityResponse with the user information JSON available as a String. The following example can be used to extract the identity JSON data with all recognised claims.

if (mobileConnectStatus.getIdentityResponse() != null)
{
    final IdentityResponse identityResponse = mobileConnectStatus.getIdentityResponse();

    if (identityResponse.getResponseJson() != null)
    {
        final String responseJson = identityResponse.getResponseJson();
    }
}

The following example shows how to add the additional Authorisation and Identity options to the Authentication call described in Using Mobile Connect Authentication, resulting in a correctly configured call to the Identity: Phone Number service.

Note: calls to Identity: Sign-up and Identity: National ID are structured in exactly the same way, but using the scopes “mc_identity_signup” and “mc_identity_nationalid” as applicable. This has been taken care of with the introduction of the Scopes.java enum which contains all of the possible MobileConnect identity options.

public final class Scopes {
    public static final String MOBILECONNECT = "openid";
    public static final String MOBILECONNECTAUTHENTICATION = "openid mc_authn";
    public static final String MOBILECONNECTAUTHORIZATION = "openid mc_authz";
    public static final String MOBILECONNECTIDENTITYPHONE = "openid mc_identity_phonenumber";
    public static final String MOBILECONNECTIDENTITYSIGNUP = "openid mc_identity_signup";
    public static final String MOBILECONNECTIDENTITYSIGNUPPLUS = "openid mc_identity_signupplus";
    public static final String MOBILECONNECTIDENTITYNATIONALID = "openid mc_identity_nationalid";
}
 

Any of the above can be used to build a String, for example:

private void populateUserInfoScopes(StringBuilder stringBuilder)
{
    if (addressSwitch != null && addressSwitch.isChecked())
    {
        stringBuilder.append(" address");
    }
    if (emailSwitch != null && emailSwitch.isChecked())
    {
        stringBuilder.append(" email");
    }
    if (phoneSwitch != null && phoneSwitch.isChecked())
    {
        stringBuilder.append(" phone");
    }
    if (profileSwitch != null && profileSwitch.isChecked())
    {
        stringBuilder.append(" profile");
    }
}   

Both Identity and User Info scopes can be built using the above methods. The final value can then be inserted in to the Builder of the scopes.

stringBuilder.toString() can now be assigned to the AuthenticationOptionsBuilder as shown previously.

AuthenticationOptions.Builder authenticationOptionsBuilder = new AuthenticationOptions.Builder().withScope(stringBuilder.toString());

            final MobileConnectRequestOptions.Builder mobileConnectRequestOptionsBuilder = new
                    MobileConnectRequestOptions.Builder();


            final MobileConnectRequestOptions mobileConnectRequestOptions = mobileConnectRequestOptionsBuilder
                    .withAuthenticationOptions(
                    authenticationOptionsBuilder.build()).build();

Further Reference

Back to top