5 JavaScript Applications

If you develop JavaScript-based mobile apps, you can use the client SDK that Oracle Mobile Cloud Enterprise (OMCe) provides for JavaScript. This SDK simplifies authentication with OMCe and provides JavaScript wrapper classes for OMCe platform APIs.

This SDK is primarily geared toward browser-based apps but can also be used for hybrid frameworks. If you develop Cordova-based apps, use the Cordova SDK. See Cordova Applications.

Getting the SDK

To get the OMCe client SDK for JavaScript, go to the Oracle Mobile Cloud Enterprise Downloads page on OTN.

Creating a Backend

You create a backend to serve as a secure gateway between your app and OMCe 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 Mobile Apps > 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.

Adding the SDK

Assuming a basic app setup, without intervening frameworks, here’s what you would do to add the JavaScript client SDK to an app:
  1. If you haven’t already done so, unzip the SDK zip.
  2. Copy mcs.min.js (and/or mcs.js) and oracle_mobile_cloud_config.js into the directory where you keep your JavaScript libraries.
  3. Fill in your mobile 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. (Optional) For RequireJS environments, load mcs.js in your app using RequireJS.

    Note:

    In addition to mcs.min.js, 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, including RequireJS. For detailed instructions on adding Sync Express to your app, see Building Apps that Work Offline Using Sync Express.

Configuring SDK Properties

To use the client SDK in a JavaScript app, add the oracle_mobile_cloud_config.js configuration file to the app and fill it in with environment details for your backend in OMCe. In turn, the SDK classes use this information to construct HTTP headers for REST calls made to OMCe.

Note:

For browser-based apps, you need to manage cross-origin resource sharing (CORS) for access to OMCe 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:

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

  • 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 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_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 (where only important events are logged). Other possible values are mcs.LOG_LEVEL.ERROR (only errors are logged) and 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 oauth, basic, facebook, and token.

    • One or more sub-elements for authentication types, each containing authentication credentials.

      You can also add the offlineEnabled key and set its value to true.

    See Authentication Properties for 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"
      }
    }
  }
};

Calling Mobile APIs

In OMCe, 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 JavaScript 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.

Loading the Backend's Configuration

Before you can make calls to OMCe APIs using the JavaScript 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);

Authenticating and Logging In

Here are some examples of how to use the Authorization class of the JavaScript client SDK in your code. These examples assume you already configured the SDK config file for the type of authentication you’re using, as described in Configuring SDK Properties.

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

First, your app needs to get a token from the third-party token issuer. The way you can obtain the token varies by issuer. For detailed information on obtaining third-party tokens and configuring identity providers in OMCe, see Third-Party SAML and JWT Tokens.

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

Securing 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 OMCe 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 more information and details on how to use the wildcard character (*), see Securing Cross-Site Requests to OMCe APIs.

Note:

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.

Calling Platform APIs

Once you include the 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);
})

Calling Custom APIs

The JavaScript 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.
  });

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

Setting 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";

Calling 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);

Adding Support for Location Services (Ionic Only)

ionic cordova plugin add cordova-plugin-geolocation

Adding 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 OMCe.

  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 OMCe and notifications profiles for Android and iOS. See Creating 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 JavaScript client SDK contains the following items:

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

  • 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_mobile_cloud_config.js — An OMCe 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 JavaScript SDK set up, you can start using it to add OMCe features to your app.