This example demonstrates how to integrate The SDK.

Download the Mobile Connect server side SDK project

Download the Mobile Connect server side project that contains the SDK and demo server side controller.

git clone https://github.com/Mobile-Connect/.net_server_side_library.git

Note: Common steps for configuration and running the server side SDK: .Net Server Side SDK setup.

Using the SDK

The Mobile Connect SDK 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 SDK 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 methods AttemptDiscovery 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.

The AttemptDiscovery method build and make discovery call:

internal static async Task<MobileConnectStatus> AttemptDiscovery(
            IDiscoveryService discovery,
            string msisdn,
            string mcc,
            string mnc,
            IEnumerable<BasicKeyValuePair> cookies,
            MobileConnectConfig config,
            MobileConnectRequestOptions options)
        {
            DiscoveryResponse response = null;
            try
            {
                DiscoveryOptions discoveryOptions = options?.DiscoveryOptions ?? new DiscoveryOptions();
                discoveryOptions.MSISDN = msisdn;
                discoveryOptions.IdentifiedMCC = mcc;
                discoveryOptions.IdentifiedMNC = mnc;
                discoveryOptions.RedirectUrl = config.RedirectUrl;
                discoveryOptions.XRedirect = config.XRedirect;

                response = await discovery.StartAutomatedOperatorDiscoveryAsync(
                    config, config.RedirectUrl, discoveryOptions, cookies);
            }
            catch (MobileConnectInvalidArgumentException e)
            {
                Log.Error(() => $"An invalid argument was passed to AttemptDiscovery arg={e.Argument}");
                return MobileConnectStatus.Error(ErrorCodes.InvalidArgument, 
                    string.Format("An argument was found to be invalid during the process. The argument was {0}.", 
                    e.Argument), e);
            }
            catch (MobileConnectEndpointHttpException e)
            {
                Log.Error(() => $"A general http error occurred in AttemptDiscovery msisdn={!string.IsNullOrEmpty(msisdn)} mcc={mcc} mnc={mnc} discoveryUrl={config.DiscoveryUrl}");
                return MobileConnectStatus.Error(ErrorCodes.HttpFailure, 
                    "An HTTP failure occured while calling the discovery endpoint, the endpoint may be inaccessible",
                    e);
            }
            catch (Exception e)
            {
                Log.Error(() => $"A general error occurred in AttemptDiscovery msisdn={!string.IsNullOrEmpty(msisdn)} mcc={mcc} mnc={mnc} discoveryUrl={config.DiscoveryUrl}");
                return MobileConnectStatus.Error(ErrorCodes.Unknown, 
                    "An unknown error occured while calling the Discovery service to obtain operator details", 
                    e);
            }

            return GenerateStatusFromDiscoveryResponse(discovery, response);
        }

The HandleUrlRedirect method handle discovery response:

internal static async Task<MobileConnectStatus> HandleUrlRedirect(IDiscoveryService discovery, IAuthenticationService authentication, IJWKeysetService jwks, Uri redirectedUrl, DiscoveryResponse discoveryResponse, 
            string expectedState, string expectedNonce, MobileConnectConfig config, MobileConnectRequestOptions options, string version)
        {
            if (HttpUtils.ExtractQueryValue(redirectedUrl.Query, "code") != null)
            {
                try {
                    return await RequestToken(authentication, jwks, discoveryResponse, redirectedUrl, expectedState, expectedNonce, config, options, VersionDetection.GetCurrentVersion(version,
                    options?.AuthenticationOptions?.Scope, discoveryResponse.ProviderMetadata));

                }
                catch (MobileConnectInvalidScopeException e)
                {
                    return e.ToMobileConnectStatus();
                }
            }
            else if (HttpUtils.ExtractQueryValue(redirectedUrl.Query, "mcc_mnc") != null)
            {
                return await AttemptDiscoveryAfterOperatorSelection(discovery, redirectedUrl, config);
            }

            string errorCode = HttpUtils.ExtractQueryValue(redirectedUrl.Query, "error") ?? ErrorCodes.InvalidRedirect;
            string errorDesc = HttpUtils.ExtractQueryValue(redirectedUrl.Query, "error_description") ?? HttpUtils.ExtractQueryValue(redirectedUrl.Query, "description") ?? string.Format("Unable to parse next step using {0}", redirectedUrl.AbsoluteUri);
            return MobileConnectStatus.Error(errorCode, errorDesc, null);
        }

This SDK allows calls to Mobile Connect without first doing a Discovery call. It is a similar process to usual Mobile Connect Authentication but instead of calls to the Discovery Service a new function MakeDiscoveryForAuthorization is used to create the DiscoveryOptions object.

To load the DiscoveryOptions object:

public async Task<DiscoveryResponse> MakeDiscoveryForAuthorization(string clientId, string clientSecret,
            string appName, OperatorUrls operatorsUrl)
        {
            Validate.RejectNullOrEmpty(clientId, "clientId");
            Validate.RejectNullOrEmpty(clientSecret, "clientSecret");
            Validate.RejectNull(operatorsUrl, "operatorsUrl");

            var discoveryService = new DiscoveryService(new DiscoveryCache(), _client);

            var providerMetadata = new ProviderMetadata();

            var discoveryGenerateResponseOptions = new DiscoveryResponseGenerateOptions(clientSecret, clientId, appName, operatorsUrl.GetListOfUrls(), operatorsUrl.GetListOfRels());

            var restResponse = new RestResponse()
            {
                StatusCode = HttpStatusCode.OK,
                Content = discoveryGenerateResponseOptions.GetJsonResponse()
            };

            try
            {
                var index = 0;
                var length = discoveryGenerateResponseOptions.Response.response.apis.operatorid.link.Count;
                for (var i = 0; i < length; i++)
                {
                    if (discoveryGenerateResponseOptions.Response.response.apis.operatorid.link[i].rel != LinkRels.OPENID_CONFIGURATION) continue;
                    index = i;
                    break;
                }

                var providerMetadataLink = discoveryGenerateResponseOptions.Response.response.apis.operatorid.link[index].href;

                if (providerMetadataLink != null)
                {
                    providerMetadata = await discoveryService.RetrieveProviderMetada(providerMetadataLink);
                }
            }
            catch (Exception exception)
            {

                throw exception;
            }

            var discoveryResponse = new DiscoveryResponse(restResponse);
            discoveryResponse.ProviderMetadata = providerMetadata;

            return discoveryResponse;
        }

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.

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 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 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.
  • Mobile Connect Version Compatibility

    The SDK implements version autodetection, this is a mechanism which helps to detect version by configuration parsing, provided values and additional analysis.

    Identify gateway supported versions:

    • If a Provider Metadata document is available then get a list of supported versions based on the mc_version value.
    • If the Provider Metadata document is not available the supported version will be mc_v1.1.

    Identify request version:

    • If the version value is not empty and the SDK supports this version (see note), then use this.
    • If the version value is empty or the SDK doesn’t support the selected version then the scope and list of supported versions (based the ID Gateway) will be analysed to detect the version of MC API, which can be used. Verification order:
      • If the list of supported versions contains mc_di_r2_v2.3 and the scope is valid for this version, then this version will be used.
      • Otherwise, if the list of supported versions contains mc_v2.0 and the scope is valid for this version, then this version will be used.
      • Otherwise, if list of supported versions contains mc_v1.1 and the scope is valid only for this version, then this version will be used.
      • Otherwise, if the list of supported versions contains only mc_v1.2 and the scope is valid for this version, then this version will be used (but a warning will indicate that version is deprecated).
      • If current scope doesn’t match with versions included in list of supported versions, the SDK will throw invalid scope exception.

    NOTE: mc_v1.1, mc_v1.2, mc_v2.0, mc_di_r2_v2.3 are supported.

    Versions and supported scopes:

    Version Supported Scopes
    mc_v1.1 "openid", "openid mc_india_tc", "openid mc_mnv_validate", "openid mc_mnv_validate_plus", "openid mc_attr_vm_share", "openid mc_attr_vm_share_hash"
    mc_v2.0 "openid mc_authn" "openid mc_authn", "openid mc_authz", "openid mc_identity_phonenumber", "opeind mc_identity_signup", "openid mc_identity_nationalid", "openid mc_india_tc", "openid mc_mnv_validate", "openid mc_mnv_validate_plus", "openid mc_attr_vm_share", "openid mc_attr_vm_share_hash"
    mc_di_r2_v2.3 "openid mc_authn" "openid mc_authn", "openid mc_authz", "openid mc_identity_phonenumber", "opeind mc_identity_signup", "openid mc_identity_nationalid", "openid mc_kyc_plain", "openid mc_kyc_hashed", "openid mc_india_tc", "openid mc_mnv_validate", "openid mc_mnv_validate_plus", "openid mc_attr_vm_share", "openid mc_attr_vm_share_hash"

    This algorithm is implemented in the VersionDetection class.

    The GetCurrentVersion method takes three parameters:

    • version (from configuration)
    • scope (from configuration)
    • ProviderMetadata (from DiscoveryResponse).

    The method parses and verifies parameters and then returns correct MC API version regarding the conditions.

    public static string GetCurrentVersion(string version, string scope, ProviderMetadata providerMetadata)
            {
                List<string> supportedVersion = GetSupportedVersions(providerMetadata);
                if (version != null && IsVersionSupported(version))
                {
                    if (!supportedVersion.Contains(version))
                    {
                        Log.Warning(() => $"Check version. It might be unsupported {version}");
                    }
    
                    return version;
                }
    
                List<string> currentScopes = StringUtils.ConvertToListBySpace(scope);
                if (supportedVersion.Contains(Version.MC_DI_R2_V2_3) & ContainsScopesV2_3(currentScopes))
                {
                    return Version.MC_DI_R2_V2_3;
                } 
                if (supportedVersion.Contains(Version.MC_V2_0) & ContainsScopesV2_0(currentScopes))
                {
                    return Version.MC_V2_0;
                } 
                if (supportedVersion.Contains(Version.MC_V1_1) & ContainsScopesV1_1(currentScopes))
                {
                    return Version.MC_V1_1;
                }
                if (supportedVersion.Contains(Version.MC_V1_2) & ContainsScopesV2_0(currentScopes) & supportedVersion.Count == 1)
                { 
                    Log.Warning("Version is deprecated");
                    return Version.MC_V1_2;
                }
    
                MobileConnectInvalidScopeException invalidScopeException = new MobileConnectInvalidScopeException(scope);
                throw invalidScopeException;
            }

    The VersionDetection.GetCurrentVersion method calls in each method of MobileConnectInterface class to detect correct version.

    internal static MobileConnectStatus StartAuthentication(IAuthenticationService authentication, DiscoveryResponse discoveryResponse, string encryptedMSISDN,
                string state, string nonce, MobileConnectConfig config, MobileConnectRequestOptions options, string version)
            {
                ...
    
                    try {
                        response = authentication.StartAuthentication(clientId, correlationId, authorizationUrl, config.RedirectUrl, state, nonce, encryptedMSISDN, authOptions, 
                        VersionDetection.GetCurrentVersion(version, options?.AuthenticationOptions?.Scope, discoveryResponse.ProviderMetadata));
                    }
                    catch (MobileConnectInvalidScopeException e)
                    {
                        return e.ToMobileConnectStatus();
                    }
                       
                ...
            }

    Using version the auto-detection mechanism in the MobileConnectInterface class ensures that the verifications and request generation in Authentication and Token Services are correct. Furthermore it allows the automatic processing of version, regardless of using only SDK or Server Side SDK.

    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.

    Mobile Connect Constants

    The SDK 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 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 MOBILECONNECT "openid"
    Authentication 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"
    KYC plain MOBILECONNECTKYCPLAIN "openid mc_kyc_plain"
    KYC hashed MOBILECONNECTKYCHASHED "openid mc_kyc_hashed"
    ATTR VM Match MOBILE_CONNECT_ATTR_VM_MATCH "openid mc_attr_vm_match"
    ATTR VM Hash MOBILE_CONNECT_ATTR_VM_MATCH_HASH "openid mc_attr_vm_match_hash"

    *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 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.

    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)

    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 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

    Important. Headless mode is not used any more. Please, use Server Initiated API instead.

    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 Authorize endpoint. A successful authentication returns an id_token containing the user’s PCR, which is unpacked and available for verification against your user register.

    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).

    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.

    public StartAuthenticationResponse StartAuthentication(string clientId, string correlationId, string authorizeUrl, string redirectUrl, string state, string nonce,
                string encryptedMsisdn, AuthenticationOptions options, string currentVersion)
            {
                Validate.RejectNullOrEmpty(clientId, "clientId");
                Validate.RejectNullOrEmpty(authorizeUrl, "authorizeUrl");
                Validate.RejectNullOrEmpty(redirectUrl, "redirectUrl");
                Validate.RejectNullOrEmpty(state, "state");
                Validate.RejectNullOrEmpty(nonce, "nonce");
    
                options = options ?? new AuthenticationOptions();
                options.Scope = options.Scope ?? "";
    
                if (options != null && !options.IsUsingCorrelationId)
                {
                    correlationId = "";
                }
    
                bool shouldUseAuthorize = options.Scope.ToLower().Equals(Constants.Scope.AUTHZ.ToLower());
    
                if (shouldUseAuthorize)
                {
                    Validate.RejectNullOrEmpty(options.Context, "options.Context");
                    Validate.RejectNullOrEmpty(options.ClientName, "options.ClientName");
                    Validate.RejectNullOrEmpty(options.BindingMessage, "options.BindingMessage");
                }
    
                if (options != null)
                {
                    KYCClaimsParameter kycClaims = options.KycClaims;
                    if (kycClaims != null)
                    {
                        bool isNamePresent = false;
                        bool isAddressPresent = false;
                        if (currentVersion.Equals(DefaultOptions.V2_3) && options.Scope.Contains(Constants.Scope.KYCPLAIN))
                        {
                            isNamePresent = StringUtils.requireNonEmpty("name || given_name and family_name",
                                kycClaims.Name, kycClaims.GivenName, kycClaims.FamilyName);
                            isAddressPresent = StringUtils.requireNonEmpty(
                                "address || houseno_or_housename, postal_code, country, town", kycClaims.Address,
                                kycClaims.HousenoOrHouseName, kycClaims.PostalCode, kycClaims.Country, kycClaims.Town);
                        }
                 
                        if (currentVersion.Equals(DefaultOptions.V2_3) && options.Scope.Contains(Constants.Scope.KYCHASHED))
                        {
                            isNamePresent = StringUtils.requireNonEmpty("name_hashed || given_name_hashed and family_name_hashed",
                                kycClaims.NameHashed, kycClaims.GivenNameHashed, kycClaims.FamilyNameHashed);
                            isAddressPresent = StringUtils.requireNonEmpty(
                                "address_hashed || houseno_or_housename_hashed, postal_code_hashed, country_hashed, town_hashed", kycClaims.AddressHashed,
                                kycClaims.HousenoOrHouseNameHashed, kycClaims.PostalCodeHashed, kycClaims.CountryHashed, kycClaims.TownHashed);
                        }
    
                        if ((isNamePresent & !isAddressPresent) | (!isNamePresent & isAddressPresent))
                        {
                            throw new MobileConnectInvalidArgumentException("(split|concatenated, plain|hashed) name or address is empty");
                        }
                    }
                }
    
                options.State = state;
                options.Nonce = nonce;
                options.CorrelationId = correlationId;
                if (options.LoginHintToken == null)
                {
                    options.LoginHint = options.LoginHint ?? LoginHint.GenerateForEncryptedMsisdn(encryptedMsisdn);
                }
    
                options.RedirectUrl = redirectUrl;
                options.ClientId = clientId;
    
                UriBuilder build = new UriBuilder(authorizeUrl);
                build.AddQueryParams(GetAuthenticationQueryParams(options, shouldUseAuthorize, currentVersion));
    
                Log.Info(() => $"Authentication URI={build.Uri.AbsoluteUri}");
                return new StartAuthenticationResponse() { Url = build.Uri.AbsoluteUri };
            }

    After that client side makes redirects session and gets the code. Client side sends this code to the SDK, which uses this code for RequestTokenAsync method performing.

    public async Task<RequestTokenResponse> RequestTokenAsync(string clientId, string correlationId, string clientSecret, string requestTokenUrl, string redirectUrl, string code)
            {
                Validate.RejectNullOrEmpty(clientId, "clientId");
                Validate.RejectNullOrEmpty(clientSecret, "clientSecret");
                Validate.RejectNullOrEmpty(requestTokenUrl, "requestTokenUrl");
                Validate.RejectNullOrEmpty(redirectUrl, "redirectUrl");
                Validate.RejectNullOrEmpty(code, "code");
    
                try
                {
                    var formData = new List<BasicKeyValuePair>()
                    {
                        new BasicKeyValuePair(Parameters.AUTHENTICATION_REDIRECT_URI, redirectUrl),
                        new BasicKeyValuePair(Parameters.CODE, code),
                        new BasicKeyValuePair(Parameters.GRANT_TYPE, DefaultOptions.GRANT_TYPE),
                        new BasicKeyValuePair(Parameters.CORRELATION_ID, correlationId)
                    };
    
                    RestResponse response = await _client.PostAsync(requestTokenUrl, RestAuthentication.Basic(clientId, clientSecret), formData, null, null);
                    var tokenResponse = new RequestTokenResponse(response);
    
                    return tokenResponse;
                }
                catch (Exception e) when (e is HttpRequestException || e is System.Net.WebException || e is TaskCanceledException)
                {
                    Log.Error(() => $"Error occurred while requesting token url={requestTokenUrl}", e);
                    throw new MobileConnectEndpointHttpException(e.Message, e);
                }
            }

    If scope value maches "profile", "email", "adderss", "phone" or "mc_identity_phonenumber", "mc_identity_signup", "mc_identity_signupplus", "mc_identity_nationalid", "mc_kyc_plain", "mc_kyc_hashed", requestUserInfo or requestIdentity respectively will be performed and the JSON response will be returned as identity response in the 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 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 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;
            }


    KYC Support for DI 2.3

    The SDK allows to use KYC product with the scope parameter set to "mc_kyc_plain" or "mc_kyc_hashed". Current version should be set to “mc_di_r2_v2.3”.
    To make a successful authorisation call, you must provide the KYC Claims that corresponds to the specified scope.

    You can use split claims "given_name", "family_name"; "houseno_or_housename", "postal_code", "town"; "given_name_hashed", "family_name_hashed"; "houseno_or_housename_hashed", "postal_code_hashed", "town_hashed" instead of concatenated "name"; "address"; "name_hashed"; "address_hashed". "birthdate" and "birthdate_hashed" are optional claims.
    The server side SDK performs a number of automatic claims validation:

    public StartAuthenticationResponse StartAuthentication(string clientId, string authorizeUrl, string redirectUrl, string state, string nonce,
                string encryptedMsisdn, SupportedVersions versions, AuthenticationOptions options, string currentVersion)
        {
           ...
           if (options != null)
                {
                    KYCClaimsParameter kycClaims = options.KycClaims;
                    if (kycClaims != null)
                    {
                        bool isNamePresent = false;
                        bool isAddressPresent = false;
                        if (currentVersion.Equals(DefaultOptions.V2_3) && options.Scope.Contains(Constants.Scope.KYCPLAIN))
                        {
                            isNamePresent = StringUtils.requireNonEmpty("name || given_name and family_name",
                                kycClaims.Name, kycClaims.GivenName, kycClaims.FamilyName);
                            isAddressPresent = StringUtils.requireNonEmpty(
                                "address || houseno_or_housename, postal_code, country, town", kycClaims.Address,
                                kycClaims.HousenoOrHouseName, kycClaims.PostalCode, kycClaims.Country, kycClaims.Town);
                        }
                 
                        if (currentVersion.Equals(DefaultOptions.V2_3) && options.Scope.Contains(Constants.Scope.KYCHASHED))
                        {
                            isNamePresent = StringUtils.requireNonEmpty("name_hashed || given_name_hashed and family_name_hashed",
                                kycClaims.NameHashed, kycClaims.GivenNameHashed, kycClaims.FamilyNameHashed);
                            isAddressPresent = StringUtils.requireNonEmpty(
                                "address_hashed || houseno_or_housename_hashed, postal_code_hashed, country_hashed, town_hashed", kycClaims.AddressHashed,
                                kycClaims.HousenoOrHouseNameHashed, kycClaims.PostalCodeHashed, kycClaims.CountryHashed, kycClaims.TownHashed);
                        }
    
                        if ((isNamePresent & !isAddressPresent) | (!isNamePresent & isAddressPresent))
                        {
                            throw new MobileConnectInvalidArgumentException("(split|concatenated, plain|hashed) name or address is empty");
                        }
                    }
                }
            ...
        }

    After successful validation claims are added to authorisation request as query parameter "claims". The value of claims parameter is presented as: {"premiuminfo": {"claim_name": {"value": "claim_value"}, ...}}
    Note: KYC product support is provided only by the Mobile Connect SDK. The mechanism of passing the claims is not integrated in the Server Side and should be implemented by Service Providers.


    Further Reference