4 Cordova Applications
If you develop hybrid apps based on the Apache Cordova framework, you can use the client SDK that Oracle Autonomous Mobile Cloud Enterprise (AMCe) provides for Cordova. This SDK simplifies authentication with AMCe and provides Cordova wrapper classes for AMCe 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.Getting the SDK
To get the AMCe client SDK for Cordova, go to the Oracle Autonomous Mobile Cloud Enterprise Downloads page on OTN.
Creating a Backend
You create a backend to serve as a secure gateway between your app and AMCe features, such as platform and custom APIs. For your app to access these resources, it authenticates with a backend.
-
Click to open the side menu and select Development > Backends.
-
Click New Backend.
-
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
Adding Support for Push Notifications
If you want to use push notifications in an app, these additional steps are required.
-
(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 AMCe.
-
(For Android) Download the generated Firebase configuration file and put it in the root of your project.
-
(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
-
(For iOS) Set up the app for notifications with APNS. See iOS: Apple Secure Certificates
-
Create the app in AMCe and notifications profiles for Android and iOS. See Creating a Notifications Profile.
-
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); }
-
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); }
Configuring SDK Properties
oracle_mobile_cloud_config.js
configuration file to the app and fill it in with environment details for your backend in AMCe. In turn, the SDK classes use this information to construct HTTP headers for REST calls made to AMCe.
Note:
If any of your apps will be browser-based, you need to manage cross-origin resource sharing (CORS) for access to AMCe 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
andoAuthTokenEndpoint
. 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 formhttps://host.domain:port
). -
logLevel
— Determines how much SDK logging is displayed in the app’s console. The default value ismcs.LOG_LEVEL.INFO
(only important events are logged). Other possible values aremcs.LOG_LEVEL.NONE
,mcs.LOG_LEVEL.ERROR
(only errors are logged) ormcs.LOG_LEVEL.VERBOSE
. -
enableLogger
— When set totrue
, logging is included in your app. -
logHTTP
— When set totrue
, 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 ofmcs.AUTHENTICATION_TYPES.oauth
,basic
,facebook
, ortoken
. -
One or more sub-elements containing authentication credentials.
-
(Optional) You can add the
offlineEnabled
key and set its value totrue
.
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 tomcs.AUTHENTICATION_TYPES.oauth
. -
At the same level as the
type
property, create a property calledoauth
and fill in theclientID
andclientSecret
credentials provided by the backend. -
At the top level of the file, supply the
oAuthTokenEndPoint
value that is supplied but without theoauth2/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 tomcs.AUTHENTICATION_TYPES.basic
. -
At the same level as the
type
property, create a property calledbasic
and fill in themobileBackendID
andanonymousKey
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 tomcs.AUTHENTICATION_TYPES.token
. -
Fill in the
mobileBackendId
andanonymousKey
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 tomcs.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 AMCe, 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:
-
Add the client SDK to your app.
-
Fill in the
oracle_mobile_cloud_config.js
with environment and authentication details for the backend. -
Add an SDK call to your app to load the configuration info.
-
Add an SDK call to your app to handle authentication.
-
Add any other SDK calls that you want to use.
Loading the Backend's Configuration
Before you can make calls to AMCe 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);
Authenticating and Logging 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, 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 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. The way you can obtain the token varies by issuer. For detailed information on obtaining third-party tokens and configuring identity providers in AMCe, 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);
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 AMCe 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 AMCe 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 setSecurity_AllowOrigin
to http://localhost:[port]
, but be sure to update the value in production.
Calling 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);
})
Calling 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.
});
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
-
Install the SDK in your project by running this command in your project folder:
npm install {path to unzipped SDK location}
-
Add import statements to your service to import SDK types:
import {IMCS} from 'mcs'
-
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' } } } };
-
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
-
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:
-
Add the declaration statement in your class:
export class ComponentClass{ mcs: IMCS = mcssdk; }
-
Initialize the SDK library with a configuration:
this.mcs.init(mcsConfig);
-
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)
-
(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 AMCe.
-
(For Android) Download the generated Firebase configuration file and put it in the root of your project.
-
(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
-
(For iOS) Set up the app for notifications with APNS. See iOS: Apple Secure Certificates
-
Create the app in AMCe and notifications profiles for Android and iOS. See Creating a Notifications Profile.
-
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); }
-
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
— An AMCe 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.