This example demonstrates how to integrate server side library.

Configuring and running the server side library

  1. Register an account or login to the Mobile Connect Developer Portal and create an application to obtain your sandbox credentials.
  2. Download the Mobile Connect server side project.

    git clone https://github.com/Mobile-Connect/.net_server_side_library.git
  3. Open the configuration file: [local path]\mobile-connect-demos\GSMA.MobileConnect.Demo.ServerSide\App_Data\OperatorData.json.

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

    Here are 12 parameters:

    {
      "clientID": your client Id,
      "clientSecret": your client Secret,
      "discoveryURL": your Discovery endpoint,
      "redirectURL": "<protocol>://<hostname>/server_side_api/discovery_callback",
      "xRedirect": "True",
      "includeRequestIP": "False",
      "apiVersion": api version: "mc_v1.1" or "mc_v1.2",
      "scope": scopes,
      "acrValues":  acr_values,
      "userInfo": "True",
      "identity": "False",
      "MaxDiscoveryCacheSize": max cache size
    }
  4. Download and install any missing dependencies.
  5. Build the project. You can configure your application (clientID, clientSecret, discoveryURL, redirectURL). You can also configure your parameters for auth request (xRedirect, . includeRequestIP, apiVersion, scope, acrValues). And You can configure cache size (maxDiscoveryCacheSize) and if you want to run or not to run get user info request and get identity request (userInfo, identity).
  6. Run the MobileConnect demo.
  7. Prepare client side application (IOS or Android application) or Demo App for Server Side application.


Using the server side application

The server side library for .Net 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 with a number of endpoints and the operator specific credentials which will need to use with this ID Gateway.
The server side library has 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 methodsAttemptDiscovery, AttemptDiscoveryAfterOperatorSelection, and handleUrlRedirect do just that, building and making the call, and then handling the response. The server side library also takes care of caching the response for re-use in a subsequent call – subject to the configured timeout.

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 server side library 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 server side library 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.

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 server side library 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”

.

Version Compatibility

Although the MNOs may support differing versions of the Mobile Connect APIs, the server side library 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.

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 server side library captures the returned applicationShortName and includes it when constructing calls to the Mobile Connect Authorisation and Identity endpoints.

Mobile Connect Constants

The server side library provides a number of constants for referencing the Mobile Connect services by scope. They are available at GSMA.MobileConnect.MobileConnectConstants , and can be called using the following syntax:

 GSMA.MobileConnect.MobileConnectConstants.MOBILECONNECTIDENTITYPHONE

The above example calls the scope "openid mc_identity_phonenumber". You can pass multiple scopes as a space-separated string; the server side library 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.

Login Hint Support

You have the option to provide the login hint to the Identity Gateway using 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 server side library 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 server side Library offers a further three functions to build it for you:

  • GenerateLoginHintMSISDN (String MSISDN)
  • GenerateLoginHintEncryptedMSISDN (String encryptedMSISDN)
  • GenerateLoginHintPCR (String PCR)

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 server side library 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 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

Using Mobile Connect Authentication

The server side library 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 server side library 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 server side library 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.

Server side application

With your configuration specified in the configuration file you have everything you need to make a successful call to the server side application.

Client side application allows to sends a request to server side application in three modes: msisdn, mcc_mnc, none

Example request:
If you are using only msisdn the request to your server side part will be: http://localhost:8080/server_side_api/start_discovery?msisdn=447700900907
When you are using mcc and mnc it will be: http://localhost:8080/server_side_api/start_discovery?mcc=907&mnc=07
If you choose None mode: http://localhost:8080/server_side_api/start_discovery
Also sourceIp can be included to request: http://localhost:8080/server_side_api/start_discovery?sourceIp=10.0.0.7

Client side application sends a GET request with client data to server side application. Then server side application makes StartDiscovery method call with your data from configuration file. This method calls AttemptDiscovery method with your parameters from config file. And then StartAuthentication method perfoms for getting authentication URL.

        [HttpGet]
        [Route("start_discovery")]
        public async Task<IHttpActionResult> StartDiscovery(string msisdn = "", string mcc = "", string mnc = "")
        {
            GetParameters();
            string sourceIp = Request.Headers.Any(h => h.Key.Equals("X-Source-IP")) ?
                Request.Headers.GetValues("X-Source-IP").ToList().FirstOrDefault() :
                string.Empty;

            var requestOptions = new MobileConnectRequestOptions { ClientIP = sourceIp };

            var status = await _mobileConnect.AttemptDiscoveryAsync(
                Request, msisdn, mcc, mnc, false, _includeRequestIP, requestOptions);

            _requestMessage = Request;

            if (HandleErrorMsg(status) == true)
            {
                status = await _mobileConnect.AttemptDiscoveryAsync(
                    Request, null, null, null, false, false, requestOptions);
            }

            if (status.DiscoveryResponse != null && 
                status.DiscoveryResponse.ResponseCode == Utils.Constants.Response_OK)
            {
                CachedParameters.sdkSession = status.SDKSession;
                var authResponse = await StartAuthentication(
                    Request, status.SDKSession, status.DiscoveryResponse.ResponseData.subscriber_id);

                return authResponse;
            }
            else
            {
                return GetHttpMsgWithRedirect(status, status.ErrorCode);
            }
        }

To generate the request parameters it uses GetParameters method:

public void GetParameters(string clientID = "", string clientSecret = "", string discoveryURL = "", string redirectURL = "",
            string xRedirect = "", string includeRequestIP = "", string scope = "", string apiVersion = "")
        {
            _apiVersion = apiVersion;
            _includeRequestIP = includeRequestIP.Equals("True");
            _cache = new ConcurrentCache();
            _restClient = new RestClient();
            _mobileConnectConfig = new MobileConnectConfig()
            {
                ClientId = clientID,
                ClientSecret = clientSecret,
                DiscoveryUrl = discoveryURL,
                RedirectUrl = redirectURL,
                XRedirect = xRedirect.Equals("True") ? "APP" : "False"
            };
            _mobileConnect = new MobileConnectWebInterface(_mobileConnectConfig, _cache, _restClient);
        }

Note:If discovery request with msisdn, mcc_mnc or source ip fails - method perform Discovery UI flow to discover operator.

1) If you selected the msisdn mode: stateDiscoveryCallback method is called. This method calles HandleUrlRedirectAsync (where a token will receive) and also RequestIdentity or RequestUserInfo if it was specified in the configuration. After you follow the redirect, and pass consent confirmation screen, redirect will be proceed by server side DiscoveryCallback method:

     

[HttpGet]
        [Route("discovery_callback")]
        public async Task<IHttpActionResult> DiscoveryCallback(
            string state = null, 
            string error = null, 
            string description = null)
        {
            if (!string.IsNullOrEmpty(error))
            {
                if (!string.IsNullOrEmpty(state))
                {
                    return await StartDiscovery();
                }

                return CreateResponse(MobileConnectStatus.Error(error, description, new Exception()));
            }

            var requestOptions = new MobileConnectRequestOptions
            {
                AcceptedValidationResults = Authentication.TokenValidationResult.Valid |
                    Authentication.TokenValidationResult.IdTokenValidationSkipped
            };

            var cachedInfo = responseChecker.getData(state);
            var authConnectStatus = await _mobileConnect.HandleUrlRedirectAsync(
                Request, 
                Request.RequestUri, 
                cachedInfo.Result.sdkSession, 
                state,
                cachedInfo.Result.nonce, 
                requestOptions);

            if (HandleErrorMsg(authConnectStatus))
            {
                RemoveSessionFromCache(discoveryCache, cachedInfo.Result.discoveryOptions);
                return CreateResponse(MobileConnectStatus.Error(
                    ErrorCodes.InvalidArgument, authConnectStatus.ErrorMessage, new Exception()));
            }

            MobileConnectStatus response = null;
            var idTokenResponseModel = 
                JsonConvert.DeserializeObject<IdTokenResponse>(authConnectStatus.TokenResponse.DecodedIdTokenPayload);

            if (idTokenResponseModel.nonce.Equals(cachedInfo.Result.nonce))
            {
                if (_operatorParams.identity.Equals("True"))
                {
                    response = await RequestUserInfo(state, authConnectStatus.TokenResponse.ResponseData.AccessToken);
                    return CreateIdentityResponse(response, authConnectStatus);
                }
                else if (_operatorParams.userInfo.Equals("True"))
                {
                    response = await RequestIdentity(state, authConnectStatus.TokenResponse.ResponseData.AccessToken);
                    return CreateIdentityResponse(response, authConnectStatus);
                }
            }
            else
            {
                response = MobileConnectStatus.Error(
                    ErrorCodes.InvalidArgument, "nonce is incorrect", new Exception());
            }

            return CreateResponse(response);
        }

2) mcc_mnc mode.
3) none mode.

If you selected the mcc_mnc mode or none mode:
you will be redirected to the operator selection page. Here you can type your msisdn and process page.
After getting URL with code and state parameters application calls token endpoint with received data and get token, that could be used in authentication process in your web application. This is proceed by MCC_MNC_DiscoveryCallback method.

  
[HttpGet]
        [Route("discovery_callback")]
        public async Task<IHttpActionResult> MCC_MNC_DiscoveryCallback(string mcc_mnc, string subscriber_id = "")
        {
            var requestOptions = new MobileConnectRequestOptions { ClientIP = "" };
            var mcc_mncArray = mcc_mnc.Split(new char[] { '_' });
            var mcc = mcc_mncArray[0];
            var mnc = mcc_mncArray[1];
            var status = await _mobileConnect.AttemptDiscoveryAsync(
                _requestMessage, "", mcc, mnc, true, _includeRequestIP, requestOptions);

            if (status.DiscoveryResponse != null)
            {
                CachedParameters.sdkSession = status.SDKSession;
                var authResponse = await StartAuthentication(
                    _requestMessage, status.SDKSession, subscriber_id);
                return authResponse;

              
            }
            else
            {
                return GetHttpMsgWithRedirect(status, status.ErrorMessage);
            }
        }

Discovery caching

Discovery response is cached in server side library with following rules:
1) After succeed Discovery request, Discovery response is cached with used mcc/mnc, msisdn or sourceIp.
2) Expiration time for Discovery Response cache is the same as "ttl" field in Discovery Response - if Discovery Response expired - that deleted from cache.
3) Next requests for Discovery with the same mcc/mnc, msisdn or sourceIp - Discovery request shouldn't be performed, Discovery response should be taken from cache.
4) If auth call respond with error - Discovery Response deleted from cache, and server side library redirect you to Discovery UI.

Using Mobile Connect Authorisation

The server side library 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 server side library 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 value is taken from Options and must match the Application Short Name.
  • 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.

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 authorisation service.

var authOptions = new MobileConnectRequestOptions
{
    Scope = MobileConnectConstants.MOBILECONNECTAUTHORIZATION,
    Context = "trans 123", //context of the transaction
    BindingMessage = "jamaica clock", //unique user recognisable message
};

MobileConnectStatus newResponse = _mobileConnect.StartAuthentication(discoveryResponse, subscriberId, state, nonce, authOptions); //same as Authentication example

If userInfo or identity parameter has True value in configuration file , requestUserInfo or requestIdentity respectively will be performed and the JSON response will be returnd to client side application. Else client side application will receive the Token JSON response.

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 server side library 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 server side library 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.

MobileConnectStatus response = await _mobileConnect.RequestIdentityAsync(discoveryResponse, accessToken, new MobileConnectRequestOptions());
// IdentityData is a JSON serializable class containing properties for all available Identity claims
// It can be replaced by any JSON serializable type, either to add additional supported claims
// or to provide a lightweight class with only the required claims
IdentityData identity = response.IdentityResponse.ResponseDataAs<IdentityData>();

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.

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

 var authOptions = new MobileConnectRequestOptions
{
    Scope = MobileConnectConstants.MOBILECONNECTIDENTITYPHONE,
    Context = "trans 123", //context of the transaction
    BindingMessage = "jamaica clock", //unique user recognisable message
};

MobileConnectStatus newResponse = _mobileConnect.StartAuthentication(discoveryResponse, subscriberId, state, nonce, authOptions); //same as Authentication example

Add the RequestIdentity() and RequestUserInfo() methods to request the identity data following a successful authorisation.

 
private async Task<MobileConnectStatus> RequestIdentity(string state = null, string accessToken = null)
        {
            var cachedInfo = responseChecker.getData(state);
            MobileConnectStatus response = null;

            try
            {
                response = await _mobileConnect.RequestIdentityAsync(Request, cachedInfo.Result.sdkSession,
                    accessToken ?? cachedInfo.Result.accessToken, new MobileConnectRequestOptions());
            }
            catch (Exception e)
            {
                if (cachedInfo.Result != null)
                {
                    return response;
                }
                response = MobileConnectStatus.Error(ErrorCodes.InvalidArgument, "state value is incorrect", e);
            }

            return response;
        }

 
 private async Task<MobileConnectStatus> RequestUserInfo(string state = null, string accessToken = null)
        {
            var cachedInfo = responseChecker.getData(state);
            MobileConnectStatus response = null;

            try
            {
                response = await _mobileConnect.RequestUserInfoAsync(Request, cachedInfo.Result.sdkSession,
                    accessToken ?? cachedInfo.Result.accessToken, new MobileConnectRequestOptions());
            }
            catch (Exception e)
            {
                if (cachedInfo.Result != null)
                {
                    return response;
                }

                response = MobileConnectStatus.Error(ErrorCodes.InvalidArgument, "state value is incorrect", e);
            }

            return response;
        }

Further Reference