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

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 Authorization or Identity endpoints.

Configuring your Project

  1. Download the Mobile Connect SDK for Java

  2. Build the SDK using Maven repository.

    cd mobile-connect-sdk
    mvn clean install
  3. Import the generated mobile-connect-sdk-2.4.6.jar into your Java project.

Using the SDK with Mobile Connect

The Mobile Connect SDK for Java 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.

Discovery

Discovery is the process of determining an end-user's Mobile Connect Identity Provider, i.e the Operator ID Gateway. The discovery response will provide you with a number of endpoints and the operator specific credentials that you will need to use with this ID Gateway. If you are working with a specific operator or know your endpoint in advance then you do not need to use the discovery service.

The SDK allows you to call a method that accepts user's data as parameters and needs MobileConnectConfig object initialized as part of the MobileConnectWebInterface object - that's enough to make a successful call to the Mobile Connect Discovery endpoint, and the methods attemptDiscovery, attemptDiscoveryAfterOperatorSelection, 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.

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

Detailed discovery methods usage described here

Back to top

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

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:

boolean 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* MOBILECONNECTIDENTITYSIGNUPPLUS "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 AttemptDiscoveryAsync, AttemptDiscoveryAfterOperatorSelectionAsync, and HandleUrlRedirectAsync 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.

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

The following procedure details the steps for creating a server application capable of calling, and handling the responses from, the Mobile Connect Authentication service. The steps don’t describe how to construct the web pages that will be needed for a client to interact with the server application beyond describing the interfaces. In order to build and test the application described, create pages using your preferred scripting language to interact with the server application.

  1. In your IDE, create a new Java file (main.java).
  2. In main.java, create a Mobile Connect controller class. This will contain all of the code you write in this procedure.

    public class App
    {
       private final MobileConnectWebInterface mobileConnectWebInterface;
    
        public App (final MobileConnectWebInterface mobileConnectWebInterface)
        {
            this.mobileConnectWebInterface = mobileConnectWebInterface;
        }
    }
  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.discovery.mobileconnect.io

    new MobileConnectConfig.Builder()
                .withClientId("<yourClientId>")
                .withClientSecret("<yourClientSecret>")
                .withDiscoveryUrl("<yourDiscoveryUrl>")
                .withRedirectUrl("<yourRedirectUrl>")
                .withXRedirect("<yourXRedirect>")
                .build();
  4. Add a method to instantiate the MobileConnectWebInterface class and pass it the configuration MobileConnectConfig.

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

    public MobileConnectWebInterface mobileConnectWebInterface(
            final MobileConnectConfig config)
        {
            return MobileConnect.buildWebInterface(config, new DefaultEncodeDecoder());
        }
  5. Add a method startDiscovery() to call the Mobile Connect Discovery service.

    public MobileConnectWebResponse startDiscovery(
        String msisdn,
        String mcc,
        String mnc,
        final HttpServletRequest request)
    {
        final MobileConnectStatus status =
            this.mobileConnectWebInterface.attemptDiscovery(request, msisdn, mcc, mnc, true, false, null);
    
        return new MobileConnectWebResponse(status);
    }

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

  6. Add a handler to capture the parameters from redirected URLs containing the results of calls to both the Discovery and Identity Gateway endpoints. The client must forward the redirected URL’s parameters, as appropriate, using a GET action.

    public MobileConnectWebResponse handleRedirect(
          String sdkSession,
          String expectedState,
          String expectedNonce,
          HttpServletRequest request)
    {
      final URI requestUri = HttpUtils.extractCompleteUrl(request);
      final MobileConnectRequestOptions options = new MobileConnectRequestOptions.Builder()
              .withAuthenticationOptions(new AuthenticationOptions.Builder()
                      .withScope(com.gsma.mobileconnect.r2.constants.Scopes.MOBILECONNECTAUTHENTICATION)
                      .withContext("demo")
                      .withBindingMessage("demo auth")
                      .build())
              .build();
      final MobileConnectStatus status =
              this.mobileConnectWebInterface.handleUrlRedirect(request, requestUri, sdkSession, expectedState, expectedNonce, options);
    
      return new MobileConnectWebResponse(status);
    }

    Each response has the action property, which contains a key specifying what the client’s next action should be, from the following list: “discovery", "operator_selection", "start_authorization", "authorization", "complete", and "error".

  7. Add a call to the Mobile Connect Authentication endpoint.

    Note: the first two null parameters correspond to state and nonce in the startAuthentication method of mobileConnectWebInterface. 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 Authorization and ID & Attributes services; where no scope is passed, the requested service defaults to Authentication.

    public MobileConnectWebResponse startAuthentication(
        String sdkSession,
        String subscriberId,
        HttpServletRequest request)
    {
        final MobileConnectStatus status =
            this.mobileConnectWebInterface.startAuthentication(request, sdkSession, subscriberId,
                null, null, null);
    
        return new MobileConnectWebResponse(status);
    }

    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 Authorization

The SDK allows you to call the Identity Gateway with the scope parameter set to “mc_authz”, which signifies an authorization 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 authorization call, you must provide the following additional parameters:

  • client_name – specifies the name of the application/service requesting authorization. This value is taken from Options and must match the Application Short Name.
  • context – specifies the reason for the authorization request, and should be built from the data describing the transaction requiring authorization. The context is displayed on the authenticating (mobile) device only.
  • binding_message– specifies a reference string to display on the device from which the authorization 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 authorization prompt displayed to the user combines all three parameters, which cannot exceed 93 bytes in total.

The following example shows how to add the additional options to the authentication call described in Using Mobile Connect Authentication, resulting in a correctly configured call to the authorization service.

public MobileConnectWebResponse startAuthentication()
{
    …

    final MobileConnectRequestOptions options = new MobileConnectRequestOptions.Builder()
        .withAuthenticationOptions(new AuthenticationOptions.Builder()
            .withScope(com.gsma.mobileconnect.r2.constants.Scopes.MOBILECONNECTAUTHORIZATION)
            .withContext("demo")
            .withBindingMessage("demo auth")
            .build())
        .build();

    …
}

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

Back to top

Using Mobile Connect Identity and Attributes

A successful call to the Authorization 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 authorization 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 authorization, the SDK provides an IdentityResponse with the user information JSON available as a property. The following example can be used to convert the JSON data to a class - IdentityData - which is provided with all recognised claims.

final MobileConnectStatus response =
            this.mobileConnectWebInterface.requestIdentity(request, discoveryResponse, accessToken);

final IdentityResponse identityResponse = response.getIdentityResponse();

The following example shows how to add the additional Authorization 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.

Add the MobileConnectRequestOptions required for Authorization and Identity: Phone Number.

public MobileConnectWebResponse startAuthentication()
{
	…
        final MobileConnectRequestOptions options = new MobileConnectRequestOptions.Builder()
            .withAuthenticationOptions(new AuthenticationOptions.Builder()
                .withScope(“openid mc_authz mc_identity_phonenumber”)
                .withContext("Demo Context")
                .withBindingMessage("Demo Message")
                .build())
            .build();

        …
    }

Add the requestIdentity() method to request the identity data following a successful authorization.

public MobileConnectWebResponse requestIdentity(
        String sdkSession,
        String accessToken,
        HttpServletRequest request)
    {
        final MobileConnectStatus status =
            this.mobileConnectWebInterface.requestIdentity(request, sdkSession, accessToken);

        return new MobileConnectWebResponse(status);
    }

Back to top

Using Mobile Connect Server-to-Server (Headless) Operation

MNOs have the option to enable headless operation in their Identity Gateway. This server-to-server configuration allows your server-side applications/services to make calls to the Mobile Connect endpoints without any user interaction via a client application or browser. Headless operation supports implementations where the user’s MSISDN is provided by a third-party system – a call centre Interactive Voice Response (IVR) system, for example.

The Mobile Connect SDK handles the configuration needed for headless operation. Following a successful Discovery response containing the URL to the MNO’s Identity Gateway, the SDK handles the call to the requested endpoint (Authentication, Authorization, or Identity) in the following ways:

  • The prompt parameter is set to “mobile”, ensuring that all user interactions are sent via the user’s mobile device.
  • The SDK waits for a response from the endpoint (in the form of a redirect to your registered redirect URL) following either a successful user authentication or an error. If the wait time exceeds the timeout interval (defaulting to two minutes, but you can set a different duration) then a timeout error is generated and returned to your application.
  • The SDK can cancel an in-progress request when instructed by your application/service.

public MobileConnectWebResponse requestHeadlessAuthentication(
    DiscoveryResponse discoveryResponse,
    String subscriberId,
    String state,
    String nonce,
    HttpServletRequest request)
{
    MobileConnectStatus headlessRequest = mobileConnectInterface.requestHeadlessAuthentication(
                request, discoveryResponse, subscriberId, state, nonce, new MobileConnectRequestOptions.Builder().build()
        );

    return new MobileConnectWebResponse(status);
}

Back to top