4 Cordova Applications

If you develop hybrid apps based on the Apache Cordova framework, you can use the client SDK that provides for Cordova. This SDK simplifies authentication with Oracle Mobile Hub and provides Cordova wrapper classes for Mobile Hub platform APIs as well as libraries for Data Offline and Sync and Sync Express.

If you are new to Cordova itself and still need to set it up on your system, you can follow the Getting Started with JET Hybrid Apps tutorial for an end-to-end look at creating a Cordova app and connecting it with a mobile backend.

Note:

This SDK supports Cordova apps for the iOS and Android platforms. Apps for Microsoft Windows are not supported.

Get the SDK

To get the client SDK for Cordova, go to the Oracle Digital Assistant and Mobile Cloud Downloads on OTN.

Create a Backend

You create a backend to serve as a secure gateway between your app and Mobile Hub features, such as platform and custom APIs. For your app to access these resources, it authenticates with a backend.
  1. Click icon to open the side menu to open the side menu and select Development > Backends.
  2. Click New Backend.
  3. Once you complete the dialog and the backend is created, keep the Settings page open.
    You’ll need to configure your app with some of this information.

Add the SDK

Assuming a basic app setup, without intervening frameworks, here’s what you would do to add the Cordova client SDK to an app:
  1. If you haven’t already done so, unzip the Cordova SDK zip.
  2. Copy mcs.js (and/or mcs.min.js), and oracle_mobile_cloud_config.js into the directory where you keep your JavaScript libraries.
  3. Fill in your backend details in oracle_mobile_cloud_config.js.
  4. Add script tags for the SDK and the configuration file in your app’s index.html file:
    <script src="lib/mcs/mcs.js"</script>
    <script src="app/oracle_mobile_cloud_config.js"</script>
  5. If you will be using notifications in your apps, install the oracle-mcs-notifications-cordova-plugin plugin:
    cordova plugin add PATH_TO_UNZIPPED_SDK/oracle-mcs-notifications-cordova-plugin
  6. (Optional) For RequireJS environments, load mcs.js in your app using RequireJS.
    If your app uses Sync Express, mcs.sync.min.js must be fetched and executed as the first script in the main page of your app, before any other script. For detailed instructions on adding Sync Express to your app, see Building Apps that Work Offline Using Sync Express.

Add Support for Push Notifications

If you want to use push notifications in an app, these additional steps are required.

  1. (For Android) Register your app for notifications on the Firebase Cloud Messaging (FCM) console. See Set Up a Firebase Cloud Messaging Client App on Android on Google’s developer site.

    When you generate the configuration file for your app, make sure you choose to enable the Cloud Messaging service.

    When generation is complete, the Project Number (aka Sender ID) and API Key are displayed. These credentials are unique to the mobile app and can’t be used to send notifications to any other app. You also need these values to get a registration token from FCM and set up the connection with the OMH service.

  2. (For Android) Download the generated Firebase configuration file and put it in the root of your project. 

  3. (For Android) If you haven’t already done so, install the notifications plugin that is supplied with the SDK: 

    cordova plugin add PATH_TO_UNZIPPED_SDK/oracle-mcs-notifications-cordova-plugin
  4. (For iOS) Set up the app for notifications with APNS. See iOS: Apple Secure Certificates

  5. Create the app in OMH and notifications profiles for Android and iOS. See Create a Notifications Profile.

  6. In your app code, register for notifications:

    ...
    document.addEventListener("deviceready", handleDeviceReady, false);
    ...
    function handleDeviceReady(){
      MCSNotificationsCordovaPlugin.onTokenRefresh(handleTokenRefresh, handleError);
    }
    ...
    function handleTokenRefresh(token){
        console.log('NotificationsService Token refreshed', token);
        mcs.mobileBackend.notifications.registerForNotifications(token, packageName, appVersion, 'FCM')
            .then(handleRegisterForNotifications)
            .catch(handleError);
    }
     
    function handleRegisterForNotifications(response){
        console.log('NotificationsService, device registered for notifications');
    }
    function handleError(error){
        console.error('NotificationsService Error', error);
    }
  7. In your app code, subscribe to notifications events:

    ...
    function handleDeviceReady(){
        MCSNotificationsCordovaPlugin.onMessageReceived(handleMessageReceived, handleError);
    }
    ...
    function handleMessageReceived(data){
        console.log('NotificationsService Message received', data);
    }
     
    function handleError(error){
        console.error('NotificationsService Error', error);
    }

Configure SDK Properties

To use the client SDK in a Cordova app, add the oracle_mobile_cloud_config.js configuration file to the app and fill it in with environment details for your backend . In turn, the SDK classes use this information to construct HTTP headers for REST calls made to the service. If any of your apps will be browser-based, you need to manage cross-origin resource sharing (CORS) for access to OMH APIs. See Securing Browser-Based Apps Against Cross-Site Request Forgery Attacks.

Package the configuration file in the same folder as the mcs.min.js file.

The file is essentially divided into the following parts:

  • Properties that apply to the configuration as a whole, such as logLevel and oAuthTokenEndpoint. These keys generally, but don’t have to, appear at the top of the file.

  • The mobileBackend property and its contents.

    You include this part if you are using a backend with the app. The SDK classes use the environment and authentication details you specify there to access the backend and construct HTTP headers for REST calls made to APIs.

The following example shows the structure of a generic oracle_mobile_cloud_config.js file:

var mcs_config = {
  "logLevel": mcs.LOG_LEVEL.NONE,
  "logHTTP": true,
  "oAuthTokenEndPoint": "OAUTH_BASE_URL",
  "mobileBackend": {
    "name": "NAME",
    "baseUrl": "BASE_URL",
    "authentication": {
      "type": mcs.AUTHENTICATION_TYPES.oauth,
      "oauth": {
        "clientId": "CLIENT_ID",
        "clientSecret": "CLIENT_SECRET"
      }
    }
  },
  "syncExpress": {
    "handler": "OracleRestHandler",
    "policies": [
      {
        "path": '/mobile/custom/firstApi/tasks/:id(\\d+)?',
      },
      {
        "path": '/mobile/custom/secondApi/tasks/:id(\\d+)?',
      }
    ]
  }
};

Here are some notes on the file’s elements.

  • oAuthTokenEndPoint — The URL of the OAuth server from where your application gets its authentication token. This key needs to be provided for all apps that rely on OAuth to authenticate. You get this from the backend’s Settings page. The endpoint should be only the base URL (in the form https://host.domain:port).

  • logLevel — Determines how much SDK logging is displayed in the app’s console. The default value is mcs.LOG_LEVEL.INFO (only important events are logged). Other possible values are mcs.LOG_LEVEL.NONE, mcs.LOG_LEVEL.ERROR (only errors are logged) or mcs.LOG_LEVEL.VERBOSE.

  • enableLogger — When set to true, logging is included in your app.

  • logHTTP — When set to true, the SDK logs the HTTP and HTTPS headers in requests and responses.

  • mobileBackend — An element containing authentication details for your backend and other optional details, such as synchronization properties.

    You get the authentication details, such as the OAuth and HTTP credentials, from the backend’s Settings page.

  • mobileBackend/baseUrl — The base URL for all APIs that you call through the backend. You get this from the backend’s Settings page.

  • mobileBackend/authentication — Contains the following sub-elements:

    • The type sub-element, with possible values of mcs.AUTHENTICATION_TYPES.oauth, basic, facebook, or token.

    • One or more sub-elements containing authentication credentials.

    • (Optional) You can add the offlineEnabled key and set its value to true.

    See Authentication Properties for details and examples of each authentication type.

For details on sync elements, see Building Apps that Work Offline Using Sync Express.

Authentication Properties

The contents and sub-elements of authentication depend on what kind of authentication the app will be using.

OAuth
  • Set the value of the type property to mcs.AUTHENTICATION_TYPES.oauth.

  • At the same level as the type property, create a property called oauth and fill in the clientID and clientSecret  credentials provided by the backend.

  • At the top level of the file, supply the oAuthTokenEndPoint value that is supplied but without the oauth2/v1/token that is appended on the backend’s Settings page.

The resulting authentication element might look something like this:

var mcs_config = {
...
  "oAuthTokenEndPoint": "BASE_OAUTH_URL_WITH_oauth2/v1/token_REMOVED",
  "mobileBackend": {
    "name": "NAME",
    "baseUrl": "BASE_URL",
    "authentication": {
      "type": mcs.AUTHENTICATION_TYPES.oauth,
      "oauth": {
        "clientId": "CLIENT_ID",
        "clientSecret": "CLIENT_SECRET"
      }
    }
  }
};
HTTP Basic
  • Set the value of the type property to mcs.AUTHENTICATION_TYPES.basic.

  • At the same level as the type property, create a property called basic and fill in the mobileBackendID and anonymousKey that are provided by the backend.

The resulting entries might look something like this:

var mcs_config = {
   ...
  "mobileBackend": {
    "name": "NAME",
    "baseUrl": "BASE_URL",
    "authentication": {
      "type": mcs.AUTHENTICATION_TYPES.basic,
      "basic": {
        "mobileBackendId": "MOBILE_BACKEND_ID",
        "anonymousKey": "ANONYMOUS_KEY"
      }
    }
  }
};
Token Exchange

If you are authenticating using a third-party token, do the following:

  • Set the value of the type property to mcs.AUTHENTICATION_TYPES.token.

  • Fill in the mobileBackendId and anonymousKey that are provided by the backend.

The resulting properties might look something like this:

var mcs_config = {
...
  "mobileBackend": {
    "name": "NAME",
    "baseUrl": "BASE_URL",
    "authentication": {
      "type": mcs.AUTHENTICATION_TYPES.token,
      "token":{
        "mobileBackendId": "YOUR_BACKEND_ID",
        "anonymousKey": "ANONYMOUS_KEY"
      }
    }
  }
};
Facebook Login
  • Set the value of the type property to mcs.AUTHENTICATION_TYPES.facebook.

  • Fill in the HTTP Basic auth credentials and/or the OAuth credentials provided by the backend.

  • Fill in the appID for the Facebook app.

  • Fill in the relevant scopes.

The resulting authentication entry might look something like this:

var mcs_config = {
  ....
  "mobileBackend": {
    "name": "NAME",
    "baseUrl": "BASE_URL",
    "authentication": {
      "type": mcs.AUTHENTICATION_TYPES.facebook,
      "facebook":{
        "appId": "YOUR_FACEBOOK_APP_ID",
        "mobileBackendId": "YOUR_BACKEND_ID",
        "anonymousKey": "YOUR_ANONYMOUS_KEY",
        "scopes": "public_profile,user_friends,email,user_location,user_birthday"
      }
    }
  }
};

Call Mobile APIs

In OMH, a backend is a logical grouping of custom APIs, storage collections, and other resources that you can use in your apps. The backend also provides the security context for accessing those resources.

Here are the general steps for using a backend in your Cordova app:

  1. Add the client SDK to your app.

  2. Fill in the oracle_mobile_cloud_config.js with environment and authentication details for the backend.

  3. Add an SDK call to your app to load the configuration info.

  4. Add an SDK call to your app to handle authentication.

  5. Add any other SDK calls that you want to use.

Load the Backend's Configuration

Before you can make calls to the service APIs using the Cordova client SDK, you need to load the configuration for the backend you are going to use. In the following snippet, mcs_config is the name of the configuration that is defined in the oracle_mobile_cloud_config.js file that you have added to your app.

mcs.init(mcs_config);

Authenticate and Log In

Here are some examples of using the Cordova client SDK’s Authorization class. These examples assume you already configured the SDK config file for the type of authentication you’re using.

OAuth and HTTP Basic

Set the authentication type for the backend to oauth (or basic):

mcs.mobileBackend.setAuthenticationType(mcs.AUTHENTICATION_TYPES.oauth);

Then add a function that calls Authorization.authenticate on the backend, passes it a user name and specifies callbacks for success and failure:

mcs.mobileBackend.authorization.authenticate(username, password).then(callback).catch(errorCallback);

If you want to use anonymous authentication, the method to call is authenticateAnonymous:

mcs.mobileBackend.authorization.authenticateAnonymous().then(callback).catch(errorCallback);
SSO with a Third-Party Token

To use SSO with a third-party token, your app first needs to get a token from the third-party token issuer.

Set the authentication type for the backend to token and then pass the token in the authorization call:

mcs.mobileBackend.setAuthenticationType(mcs.AUTHENTICATION_TYPES.token);
mcs.mobileBackend.authorization.authenticate(token).then(callback).catch(errorCallback);
Facebook

Set the authentication type for the backend to facebook and then call authenticate():

mcs.mobileBackend.setAuthenticationType(mcs.AUTHENTICATION_TYPES.facebook);
mcs.mobileBackend.authorization.authenticate().then(callback).catch(errorCallback);

Secure Browser-Based Apps Against Cross-Site Request Forgery Attacks

If any of your apps will be browser-based, you need to manage cross-origin resource sharing (CORS) for access to APIs to protect against Cross-Site Request Forgery (CSRF) attacks. Do this by setting the Security_AllowOrigin environment to either disallow (the default value) or to a comma-separated whitelist of trusted URLs from which cross-site requests can be made. For convenience, during the development of a browser-based application or during testing of a hybrid application running in the browser, you can set Security_AllowOrigin to http://localhost:[port], but be sure to update the value in production.

Call Platform APIs

Once you include the Cordova client SDK libraries in your application, and adjust configuration settings, you’re ready to use the SDK classes in your apps.

Here’s an example of how you could use these classes to get an object from a Storage collection in the mobile backend:

mcs.mobileBackend.storage.getCollection(<collection id>)
.then(function(collection){
  return collection.getObject(<object id>, ‘blob’);
})
.then(function(object){
  console.log(object);
})
.catch(function(response){
  console.error(response);
})

Call Custom APIs

The Cordova client SDK provides the CustomCode class to simplify the calling of custom APIs. You can call a REST method (GET, PUT, POST, or DELETE) on an endpoint where the request payload is JSON or empty and the response payload is JSON or empty.

To call a custom API endpoint, you could use something like this:

mcs.mobileBackend.CustomCode.invokeCustomCodeJSONRequest("TaskApi1/tasks/100" , "GET" , null).then(function(response){
    //The response parameter returns the status code and HTTP payload from the HTTP REST Call.
    console.log(response);
    // Example: { statusCode: 200, data: {} }
    //Depends on the response format defined in the API.
  }).catch(function(response){
  //The response parameter returns the status code and HTTP payload, if available, or an error message, from the HTTP REST Call.
  console.log(response);
  /*
    Example:
      { statusCode: 404,
        data: {
      "type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1",
        "status":404,"title":"API not found",
        "detail":"We cannot find the API cordovaJSApi2 in Mobile Backend CordovaJSBackend(1.0). Check that this Mobile Backend is associated with the API.",
        "o:ecid":"005Bojjhp2j2FSHLIug8yf00052t000Jao, 0:2", "o:errorCode":"MOBILE-57926", "o:errorPath":"/mobile/custom/cordovaJSApi2/tasks" } }
   */
  //Depends on the response format defined in the API.
  });

Use TypeScript

It is also possible to use TypeScript objects with the Cordova and JavaScript client SDKs.

Here are some basic steps and examples for using TypeScript with the SDK. The examples assume your app is using the Ionic framework (though you can also use TypeScript without it).

Set Up the SDK

  1. Install the SDK in your project by running this command in your project folder:

    npm install {path to unzipped SDK location}
  2. Add import statements to your service to import SDK types:

    import {IMCS} from 'mcs'
  3. Create the configuration file for the app:

    import {IMCS,
      IOracleMobileCloudConfig,
      IMobileBackendConfig,
      IAuthenticationConfig,
      IBasicAuthConfig,
      IOAuthConfig,
      import * as mcssdk from 'mcs'
    const mcs: IMCS = mcssdk;
    
    export const mcsConfig: IOracleMobileCloudConfig = {
      logLevel: mcs.LOG_LEVEL.NONE,
      logHTTP: true,
      oAuthTokenEndPoint: 'OAUTH_URL',
      mobileBackend: <IMobileBackendConfig>{
        name: 'NAME',
        baseUrl: 'BASE_URL',
        authentication: <IAuthenticationConfig>{
          type: mcs.AUTHENTICATION_TYPES.basic,
          basic: <IBasicAuthConfig>{
            mobileBackendId: 'MOBILE_BACKEND_ID',
            anonymousKey: 'ANONYMOUS_KEY'
          }
        }
      }
    };
  4. Import the configuration into the app. If the above file is called mcs-config.ts, the import would look like :

    import { mcsConfig } from "../mcs-config";

Call Mobile APIs

  1. Add these import statements to your service or component:

    import {IMCS} from 'mcs';
    import * as mcssdk from 'mcs';  And in your class add declaration statement: 
  2. Add the declaration statement in your class:

    export class ComponentClass{
       mcs: IMCS = mcssdk; 
    }
  3. Initialize the SDK library with a configuration: 

    this.mcs.init(mcsConfig);
  4. Call backend functionality: 

    this.mcs.mobileBackend.setAuthenticationType(this.mcs.AUTHENTICATION_TYPES.basic);
    this.mcs.mobileBackend.authorization.authenticate(username, password);

Add Support for Location Services (Ionic Only)

ionic cordova plugin add cordova-plugin-geolocation

Add Support for Push Notifications (Ionic only)

  1. (For Android) Register your app for notifications on the Firebase Cloud Messaging (FCM) console. See Set Up a Firebase Cloud Messaging Client App on Android on Google’s developer site.

    When you generate the configuration file for your app, make sure you choose to enable the Cloud Messaging service.

    When generation is complete, the Project Number (aka Sender ID) and API Key are displayed. These credentials are unique to the mobile app and can’t be used to send notifications to any other app. You also need these values to get a registration token from FCM and set up the connection with OMH.

  2. (For Android) Download the generated Firebase configuration file and put it in the root of your project. 

  3. (For Android) If you haven’t already done so, install the notifications plugin that is supplied with the SDK: 

    cordova plugin add PATH_TO_UNZIPPED_SDK/oracle-mcs-notifications-cordova-plugin
  4. (For iOS) Set up the app for notifications with APNS. See iOS: Apple Secure Certificates.

  5. Create the app and notifications profiles for Android and iOS. See Create a Notifications Profile.

  6. In your app code, register for notifications:

    ...
    MCSNotificationsCordovaPlugin.onTokenRefresh(this.handleTokenRefresh.bind(this), this.handleError.bind(this));
    ...
    handleTokenRefresh(token: string){
        console.log('NotificationsService Token refreshed', token);
        this.mcs.mobileBackend.notifications.registerForNotifications(token, packageName, appVersion, 'FCM')
            .then(this.handleRegisterForNotifications.bind(this))
            .catch(this.handleError.bind(this));
    }
    
    handleRegisterForNotifications(response: INetworkResponse){
        console.log('NotificationsService, device registered for notifications');
    }
    handleError(error: any){
        console.error('NotificationsService Error', error);
    }
  7. In your app code, subscribe to notifications events:

    ...   
    MCSNotificationsCordovaPlugin.onMessageReceived(this.handleMessageReceived.bind(this), this.handleError.bind(this));
    ...
    handleMessageReceived(data: any){
        console.log('NotificationsService Message received', data);
    }
    handleError(error: any){
        console.error('NotificationsService Error', error);
    }

Libraries

The Cordova client SDK includes the following items:

  • jsdocs.zip — The compiled documentation for the library.

  • loki-cordova-fs-adapter — A plugin used for Sync Express feature for Cordova to extend amount of available storage.

  • mcs.js — The uncompressed version of the SDK. This version contains code comments and is best used as you are developing and debugging your app.

  • mcs.sync.js — The uncompressed version of the SDK Data Offline and Sync and Sync Express libraries.

  • mcs.min.js — The compressed version of the SDK. Use this version when you deploy the completed app.

  • mcs.sync.min.js — The compressed version of the SDK Data Offline and Sync and Sync Express libraries.

  • oracle-mcs-notifications-cordova-plugin — A Cordova plugin that enables iOS and Android notifications.

  • oracle_mobile_cloud_config.js — A Mobile Hub configuration file, in which you can insert environment and authentication details for the mobile backends that your app will access.

  • types — Contains TypeScript definitions for the SDK’s modules and plugins.

Next Steps

Once you have the Cordova SDK set up, you can start using it to add features to your app.