Chapter 4. Integrating RHMAP With Other Services

4.1. Introduction to MBaaS Services

MBaaS Services are cloud/web applications that provide shared functionalities that can be used by multiple cloud applications within multiple projects. Typical use cases include:

  • providing APIs to access third-party services. For example, multiple projects have a requirement to send SMS messages. You can create a service to provide the APIs to send SMS messages and that service can be accessed by multiple projects.
  • providing APIs to legacy customer backend systems For example, you may have legacy systems that perform user authentication. You can create a service that provides a consistent, modern set of APIs for projects to consume, hiding all the details about how to access the legacy systems.
Note

MBaaS Services are not designed to be used by Client Apps directly: For example, an iOS app does not call an MBaaS service directly. A Client App calls the associated Cloud App, then the Cloud App sends requests to one or more MBaaS services.

Benefits of using MBaaS services include:

  • improving code reusability. This is especially important if it is complicated to access the external services.
  • protecting sensitive information. Sometimes user credentials are required to access the external services. Using services eliminates the requirement to share the credentials with multiple project developers.

4.2. Using SAML for Authentication

4.2.1. Overview

This tutorial demonstrates an example of using SAML authentication in a mobile application. Even though SAML is currently not available as an authentication policy in Red Hat Mobile Application Platform (RHMAP), we provide templates which can be used as a starting point for your own solution.

The sample solution for SAML authentication consists of both the server-side logic and Client Apps:

Client Apps are provided for each platform:

4.2.2. Introduction to SAML

To explain the structure of the provided templates, let’s first take a brief look at the concepts of SAML. There are three actors in a SAML authentication scenario:

  • Principal — the user that is trying to access a protected resource provided by the Service Provider
  • Service Provider (SP) — a web application which provides a service to the Principal
  • Identity Provider (IdP) — a web service with the sole purpose of verifying the identity of the Principal and providing identity assertions to the Service Provider

These actors interact in the process of authentication based on several assumptions:

  • The Principal never shares his password or any other secrets with the Service Provider.
  • The Identity Provider is trusted by both the Principal and the Service Provider.
  • The Identity Provider can supply identity assertions to many Service Providers, thus enabling Single Sign-On (SSO).

4.2.3. Setting Up the Templates

First, you’ll create the SAML Service Cloud Service from the provided template. It’s the core component of the solution, acting as the Service Provider. The actual service provided in this example is showing the user details at the endpoint /session/valid. There are several other endpoints to support the SAML authentication process:

  • /login — Redirects to the login screen of the IdP.
  • /session/login_host — Returns the URL of the login screen of the IdP.
  • /login/callback — The IdP posts an identity assertion to this endpoint, indicating a login success or failure.
  • /login/ok — The Client App gets redirected to this URL as an indication of login success.

Although the service is configured to use Active Directory Federation Services 2.0 (ADFS) as the IdP, it can be configured to use any other SAML 2.0 compliant IdP with only minor adjustments.

4.2.3.1. Create the SAML Service

  1. In the Studio, navigate to Services & APIs and click Provision MBaaS Service/API.
  2. Find the SAML Service template, click Choose, enter any name (for example, "SAML Service"), and click Create.
  3. Fill in the configuration details as follows:

    • SAML_ISSUER — Leave blank for now.
    • SAML_CALLBACK_URL — Leave blank for now.
    • SAML_ENTRY_POINT — Enter the URL to your ADFS endpoint.
    • SAML_AUTHN_CONTEXT — Enter the value urn:federation:authentication:windows.
    • SAML_CERT — For this demo, this can be left blank.
  4. Click Next and wait until the service gets created. Then click Finish.

After the service is created and deployed, SAML_ISSUER and SAML_CALLBACK_URL need to be configured.

  1. In the Service Details page, look at the Current Host field and note its value. We’ll refer to it in this example as <mbaas-host>. Also, note the value of Service ID.
  2. Click Environment Variables in the menu on the left side.
  3. In the App Environment Variables section, set the following value for both variables — SAML_ISSUER and SAML_CALLBACK_URL — replacing <mbaas-host> with the value found in step 1:

    <mbaas-host>/login/callback

4.2.3.2. Set Up the Project

First, create the project:

  1. In the Studio, navigate to Projects and click New Project.
  2. Select the SAML Example Project, click Choose, enter any name (for example, "SAML Example"), and click Create.
  3. After the project gets created, click Finish.

Next, you have to associate the previously created SAML Service with the project:

  1. In the MBaas Services column of the SAML Example project, click + to add a new service.
  2. Look for the previously created SAML Service, click it, and at the bottom of the screen, click Associate Services.

The Cloud App needs to have a reference to the SAML Service. Create an environment variable to point to it:

  1. Navigate to the SAML Cloud Cloud App, and enter the Environment Variables section on the left-hand side.
  2. In the App Environment Variables section, click Add Variable, enter the following values, and click Create:

    • Name: SAML_SERVICE
    • Value: the previously noted Service ID of the SAML Service
  3. Click Push Environment Variables to propagate the environment variables to the runtime environment.

Now the apps are ready to be built, deployed, and tested.

4.2.4. How It Works

Let’s take a look at what happens during the authentication process.

When you click the Sign In button, the Client App calls the sso/session/login_host endpoint to retrieve the URL of the login screen of the IdP. This URL is then opened in an in-app browser, to let you authenticate with the IdP.

JavaScript

$('.sign-in-button').on('click', function(e) {
  $fh.cloud({
    path: 'sso/session/login_host',
    method: "POST",
    data: {
      "token": $fh._getDeviceId()
    }
  },
  function(res) {
    console.log('sso host:' + res.sso);
    var browser = cordova.InAppBrowser.open(res.sso, '_blank', 'location=yes');
...

Android

JSONObject params = new JSONObject();
params.put(TOKEN, Device.getDeviceId(getApplicationContext()));

FHCloudRequest request = FH.buildCloudRequest(
  "sso/session/login_host", "POST", null, params);
request.executeAsync(new FHActCallback() {
  @Override
  public void success(FHResponse res) {
    Log.d(TAG, "FHCloudRequest (login_host) - success");
    String ssoStringURL = res.getJson().getString("sso");
    Log.d(TAG, "SSO URL = " + ssoStringURL);
    SAMLActivity.this.displayWebView(ssoStringURL);
  }
...

iOS

NSString* deviceID = [[FHConfig getSharedInstance] uuid];
NSMutableDictionary __params = [NSMutableDictionary dictionary];
params[@"token"] = deviceID;
FHCloudRequest __cloudReq = [FH buildCloudRequest:@"sso/session/login_host" WithMethod:@"POST" AndHeaders:nil AndArgs: params];

// Initiate the SSO call to the cloud
[cloudReq execWithSuccess:^(FHResponse _success) {
  NSLog(@"EXEC SUCCESS =%@", success);
  NSDictionary_ response = [success parsedResponse];
  NSString* urlString = response[@"sso"];
  NSURL* loginUrl = [[NSURL alloc] initWithString:urlString];
  // Display WebView
  FHSAMLViewController *controller = [[FHSAMLViewController alloc] initWithURL:loginUrl];
  [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:controller animated:YES completion:nil];
...

Windows

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var response = await FHClient.GetCloudRequest("sso/session/login_host", "POST", null, GetRequestParams()).ExecAsync();

    var resData = response.GetResponseAsJObject();
    var sso = (string)resData["sso"];
    if (!string.IsNullOrEmpty(sso))
    {
        webView.Visibility = Visibility.Visible;
        webView.Navigate(new Uri(sso));
  }
}

After you enter the credentials required by the IdP and submit the login form, the IdP will post an identity assertion back to the /login/callback endpoint of the SAML Service.

The SAML Service then does the following:

  • associates the received SAML assertion with the user’s token, which is passed in the HTTP session
  • persists data from the SAML assertion
  • redirects the user to /login/ok, which signals an authentication success to the Client App

Once the user is successfully logged in, the in-app browser is closed, and the Client App can use the service provided by the Service Provider — call sso/session/valid to fetch the user details.

JavaScript

$fh.cloud({
  path: 'sso/session/valid',
  method: "POST",
  data: {
    "token": $fh._getDeviceId()
  }
},
function(details) {
  $('.first_name').text(details.first_name);
  $('.last_name').text(details.last_name);
  $('.email').text(details.email);
  $('.expires').text(details.expires);
},
...

Android

JSONObject params = new JSONObject();
params.put(TOKEN, Device.getDeviceId(getApplicationContext()));

FHCloudRequest request = FH.buildCloudRequest(
  "sso/session/valid", "POST", null, params);
  request.executeAsync(new FHActCallback() {
    @Override
    public void success(FHResponse res) {
      Log.d(TAG, "FHCloudRequest (valid) - success");
      User user = new User();
      user.setFirstName(res.getJson().getString("first_name"));
      user.setLastName(res.getJson().getString("last_name"));
      user.setEmail(res.getJson().getString("email"));
      user.setExpires(res.getJson().getString("expires"));

      Log.d(TAG, user.toString());

      SAMLActivity.this.displayUserData(user);
...

iOS

NSString* deviceID = [[FHConfig getSharedInstance] uuid];
NSMutableDictionary __params = [NSMutableDictionary dictionary];
params[@"token"] = deviceID;
FHCloudRequest __cloudReq = [FH buildCloudRequest:@"sso/session/valid" WithMethod:@"POST" AndHeaders:nil AndArgs: params];

// Initiate the SSO call to the cloud
[cloudReq execWithSuccess:^(FHResponse _success) {
  NSDictionary_ response = [success parsedResponse];
  // Manage next UI view controller
  [ self performSegueWithIdentifier: @"showLoggedIn" sender: response];
} AndFailure:^(FHResponse *failed) {
  NSLog(@"Request name failure =%@", failed);
}];

Windows

var response = await FHClient.GetCloudRequest("sso/session/valid", "POST", null, GetRequestParams()).ExecAsync();
if (response.Error == null)
{
  var data = response.GetResponseAsDictionary();
  name.Text = string.Format("{0} {1}", data["first_name"], data["last_name"]);
  email.Text = (string) data["email"];
  expires.Text = ((DateTime) data["expires"]).ToString();
}
else
{
  await new MessageDialog(response.Error.ToString()).ShowAsync();
}

4.3. Staging Cloud Apps to RedHat OpenShift Online PaaS

Overview

The intention of this guide is to provide step-by-step instructions for using OpenShift Online as an MBaaS target in the Red Hat Mobile Application Platform (RHMAP) and deploying applications to it.

4.3.1. What is OpenShift Online?

OpenShift Online is Red Hat’s public cloud application development and hosting platform that automates the provisioning, management and scaling of applications.

4.3.1.1. How Does OpenShift Online Integrate with RHMAP?

OpenShift Online users can use their OpenShift Online credentials to log in to the RHMAP and use their available OpenShift Online gears as an MBaaS target for Cloud Apps and services. MBaaS targets are containerised infrastructure that Cloud Apps and their associated services can be deployed to. One or more MBaaS targets can also be collected into an Environment. Users can then create multiple environments (with each environment having one or more MBaaS targets), to enable different stages of development (for example Dev, UAT, and Production environments) and Project Lifecycle Management.

In addition, all operations such as provisioning, logging, and endpoint security relating to MBaaS Services also apply to OpenShift Online MBaaS’s. For more information on these operations see the MBaaS Services Product Features page.

OpenShift Online Components

4.3.1.2. How Does RHMAP Affect my Available OpenShift Online Gears?

RHMAP applications are treated no differently than any other applications you would deploy to OpenShift Online. You may use some or all of your available gears to deploy RHMAP cloud and web applications, and you are only restricted by the number of gears you have available. As with any application running on OpenShift Online, the number of available gears and features depends on the current plan you have. For more details on how the RHMAP utilizes OpenShift Online gears, refer to the gears section.

4.3.1.3. Limitations

Using OpenShift Online as an MBaaS target with RHMAP is currently available as a developer preview and is not recommended for use in a production environment at this time.

4.3.2. Getting Started

All you need to get started is an OpenShift Online Account. You can use your existing account or create a new one.

Note

This only works when using an OpenShift Online account to log in to RHMAP. This feature is not available on existing RHMAP accounts.

4.3.2.1. Initial Login and Setup

Once you have an OpenShift Online account, you may then use those credentials to log in to RHMAP. The first time you log in using your OpenShift Online account, RHMAP will guide you through the setup process. On subsequent logins, you will be directed to RHMAP without going through the setup process.

Note

In order to keep up with demand, we are rolling out access by invite only. You may register your interest using the provided link on the login page and will be sent an invite email as soon as space becomes available. Your invite email will contain the appropriate login link (containing an access token) to grant you access. You must use this link to initially access the login page in order to log in.

To start the setup process:

  1. Navigate to RHMAP OpenShift Online login page and click Request an Invite.
  2. Fill in the appropriate details in the sign up form (including your Promotion Code if available) and click Sign Up.

    OpenShift Sign Up

  3. Once you receive you invite email, navigate to RHMAP via the link provided in your invite email and login using your OpenShift Online Credentials.
  4. After you successfully log in, RHMAP will ask you to create a domain name. Enter the desired name of your domain and click Create.
  5. RHMAP will then create your domain and begin the required setup process automatically. Essentially, RHMAP will create an Authorization Token and Public Key, which will allow RHMAP to communicate with your OpenShift Online gears and deploy applications on your behalf.

Once the automated setup process is complete, RHMAP is now connected to your OpenShift Online account. At this point, OpenShift Online should appear as an MBaaS target when deploying any cloud application:

OpenShift Online MBaaS

To illustrate how to use OpenShift Online as an MBaaS target, we will walk through creating a new sample application from a template and deploying the cloud portions to OpenShift Online.

4.3.2.2. Creating a Sample Application

To create a new application:

  1. Click on Projects at the top-left of the screen.
  2. Click on the New Project button on the left side of the screen.
  3. Select a project with at least one cloud component (for example Hello World Project).
  4. Enter a name for the project and click the Create button on the right side of the screen.
  5. Once the project is done being created, click the Finish button at the bottom of the screen.
  6. You should now be on the details page of the project.

4.3.2.3. Deploying a Cloud App to OpenShift Online using RHMAP

To deploy a Cloud App to OpenShift Online:

  1. If you’re not already on the main details section for your Cloud Apps, navigate to it.
  2. Choose a cloud or web app to deploy to OpenShift Online (for example Cloud App).
  3. Notice on the details page of the app that OpenShift is listed next to MBaaS Deploy Targets.

    OpenShift Online MBaaS

  4. Click on Deploy on the left side of the screen.
  5. Click on the Deploy Cloud App button at the bottom of the screen.

    OpenShift Online MBaaS

  6. This will start the deployment and show the status.

    Note

    Deploying to OpenShift Online may take a long time (that is, several minutes) for the initial deployment. Subsequent deployments of the same app will take significantly less time. Once a deployment has been started, if you do not wish to follow the status you may navigate away from the page, and the app will continue to deploy to the Environment.

    Note

    You may receive a warning related to running out of gears. This occurs when you have no available gears left on your OpenShift Online account. You may need remove other applications from your OpenShift Online account to free up gears.

    OpenShift Online MBaaS

  7. Once the deployment has successfully completed, return to the app details page by clicking on Details on the left side of the screen.
  8. To verify the app has been deployed click on the link next to Current Host.
  9. You can also log in to your OpenShift Online account to see the app deployed there as well.

    OpenShift Online Console

4.3.2.4. Deploying a Cloud App to OpenShift Online using fhc

Note

This section makes use of the fhc command line tool. For more details on installing and using fhc, see the Local Development documentation.

In order to use fhc to deploy Cloud Apps to OpenShift Online, you will need to perform the following operations:

  1. Set your target and log in.
  2. Verify the OpenShift Online MBaaS target.
  3. Obtain the ID of the environment you want to deploy to.
  4. Obtain the ID of the app you want to deploy.
  5. Deploy your app using the stage operation.

To set your target and login:

To verify the OpenShift Online MBaaS target, you can list your currently configured MBaaS services by running:

$ fhc admin mbaas list

Which will will yield something like:

IDURLService KeyUsernamePasswordModified

openshift-jsmith-email-com-enJo

https://openshift.redhat.com

undefined

jsmith@email.com

undefined

a few seconds ago

To obtain the ID of the environment you want to deploy to, you can list your available environments by running:

$ fhc admin environments list

Which will will yield something like:

IDLabelDeploy on CreateDeploy on UpdateMBaaS TargetsModified

production-openshift-jsmith-email-com-enjo

Production

undefined

undefined

openshift-jsmith-email-com-enJo

7 days ago

development-openshift-jsmith-email-com-enjo

Development

undefined

undefined

openshift-jsmith-email-com-enJo

7 days ago

To obtain the ID of the app you wish to deploy, you must first obtain the ID for the project its contained in. You can list the current projects by running:

$ fhc projects

Which will yield something like:

IDTitleNo. AppsLast Modified

wp3nlgt2jr5lvymx62tayp5z

project1

2

2 hours ago

piilhyeyqpad4nlgyveo6a43

project2

2

a day ago

You can now use the project’s ID to obtain the app’s ID via the apps command:

fhc apps <projID>

For example, if your app was contained in project1 you would run the following:

$ fhc apps wp3nlgt2jr5lvymx62tayp5z

Which will yield something like:

IdTitleDescriptionTypeGitBranch

wp3nlgrxlyzbgvwfjnmulnat

Cloud App

 

cloud_nodejs

git@example.feedhenry.net:openshift/project1-Cloud-App.git

master

wp3nlgudwgejhnzbuj5twsus

Cordova App

 

client_hybrid

git@example.feedhenry.net:openshift/.git

 

Lastly, using the ID of the app and the environment, you can use the stage command to deploy the app to OpenShift Online:

fhc app stage --app=APP-ID --env=ENV-ID

For example, if we wanted to deploy Cloud App from project1 to Development:

fhc app stage --app=wp3nlgrxlyzbgvwfjnmulnat --env=development-openshift-jsmith-example-com-enjo

When complete, it should yield something like:

{
  "action": {},
  "cacheKey": "CloudAppdevelnat-openshiftdeploy",
  "error": "",
  "log": [],
  "status": "complete"
}

4.3.3. How it works together

For RHMAP to treat your OpenShift Online gears as an MBaaS target, RHMAP must first establish a connection to OpenShift Online. This connection is setup when you login to RHMAP for the first time with your OpenShift Online credentials. RHMAP uses your credentials to login to OpenShift Online on your behalf, exchange authorization tokens, and setup SSH keys, which enables future communication between RHMAP and OpenShift Online. RHMAP then automatically configures OpenShift Online as an MBaaS target and makes it available to your projects.

Once the initial configuration is complete and your RHMAP projects can use the OpenShift MBaaS target, you may start deploying RHMAP Cloud Apps to OpenShift Online. These apps are treated just like any other OpenShift Online application with the added benefit of being integrated with RHMAP. For instance, deployments, application logging, and other operations may still be handled from RHMAP, but you may also connect directly to the application running in OpenShift Online via SSH. You may also view details of the application once its deployed directly from the OpenShift Online console.

4.3.3.1. Gears

Since RHMAP Cloud Apps deployed to OpenShift Online are treated the same as other applications deployed to OpenShift Online, they count towards and are limited by the number of available gears. The number of gears may vary depending on the plan you have. If you attempt to deploy a Cloud App from RHMAP, but do not have enough available gears, you will receive the following message:

OpenShift Online No Gears

In order to resolve this, you may consider upgrading your account or deleting another application running on OpenShift Online.

4.3.3.2. Environments

When logging in to RHMAP using your OpenShift Online credentials, it comes configured with two environments: Development and Production. You may switch between these environments by using the menu in the top right of the screen when view the details of a cloud application:

OpenShift Online Environments

For an overview of all Cloud App deployments accross all environments, click on the Lifecycle Management section of the project at the top of the screen:

OpenShift Online Lifecycle Management

Note that each application in each environment will receive their own gears. For example, if a project had two Cloud App, App1 and App2, and each required one gear, to run App1 and App2 in Development and Production would require four gears.

Note

At this time, when using RHMAP with OpenShift Online, you may not configure additional environments beyond the provided Development and Production.

4.3.3.3. Logging and Debugging

Viewing logs and troubleshooting for Cloud Apps deployed to OpenShift Online may be done from either RHMAP or from the OpenShift Online tools.

OpenShift Tools

OpenShift offers the ability to login and troubleshoot applications via SSH. To locate your Cloud App’s SSH URL:

  1. Navigate to your project.
  2. Click on the desired Cloud App.
  3. Click on Details on the left side of the screen.
  4. The SSH URL is found next to the SSH URL field. OpenShift Online SSH URL
Note

The SSH URL field is only available for Cloud Apps deployed to OpenShift Online. For more details on connecting to OpenShift using SSH, see the OpenShift SSH help page.

For more details on using SSH as well as the rest of the OpenShift Online tools, see the official documentation.

RHMAP Tools

To view a Cloud App’s logs from RHMAP:

  1. Navigate to your project.
  2. Click on the desired Cloud App.
  3. Click on Logs on the left side of the screen.

For more details on debugging applications with RHMAP, see the debugging guide.

4.3.3.4. Deleting Apps Deployed to OpenShift Online

Cloud apps must be deleted from RHMAP side. RHMAP will automatically handle deleting Cloud Apps from OpenShift Online.

To delete Cloud Apps from RHMAP:

  1. Navigate to your desired project.
  2. Choose the Cloud App you want to delete.
  3. In the Details section, click on Delete App at the bottom of the screen.
Note

If you delete an application in OpenShift Online without deleting it in RHMAP and attempt to redeploy to OpenShift Online, you may receive the following message error: "Error deploying App to OpenShift: Error disabling auto deploy: Application 'XXXXXXXXXXXXXXXXXXXXXXXX' not found. (404)"

4.3.3.5. SSH Keys

When first logging in to RHMAP with your OpenShift Online credentials, RHMAP performs an authentication and authorization exchange with OpenShift Online and adds a Public Key to your OpenShift Online account. RHMAP then uses that Public Key to deploy Cloud Apps to OpenShift Online via SSH. All keys associated with your OpenShift Online account may be viewed by going to your account’s settings page.

In cases where the Public Key generated by RHMAP expires or is removed from your OpenShift Online account, you may receive the following message:

OpenShift Online No Public Key

To resolve this issue, log out of RHMAP and log back in. RHMAP will create a new Public Key and use it going forward for deployments.

Alternatively, you may be prompted prior to performing a deployment to re-generate your access token:

OpenShift Online No Public Key

Enter your OpenShift Online credentials and click Re-Generate Access Tokens.

4.3.3.6. Domains

Domains are a part of an OpenShift Online application’s URL (for example myApplication-domain.example.com) and many applications may be deployed to a single domain. The number of domains that a user may define depends on their current plan. For more information on domains and how to manage them, see the OpenShift Online documentation.

4.4. Setting up an Auth Policy with Google OAuth

4.4.1. Google OAuth Apps

In order to perform authentication for your app’s users against Google’s OAuth service, there are a couple of steps you will need to go through first.

  • First you will first need to set up an app with Google using the Google API console. When creating an app choose web application. Don’t worry too much about the details as they can be updated afterwards. Once your app has been created take note of your client id and client secret provided by Google.
  • The client id will look something like : 00000000000.apps.googleusercontent.com
  • The secret will be a hash of numbers and digits.

If you look at the image below you will see in red where these items will appear in Google’s console.

Google Console

  • Next, log in to the Studio as a user in a team with Domain Administration rights and click on the Auth Policies tab. Click the create button to make a new policy. Select the type as OAuth2 and fill in the details given to you by Google.

    Note

    In order to access the Auth Policies tab in the Studio, the User must be a member of a Team(s) with View & Edit Permissions set for Authorization Policy

  • Add the callback url provided in the Auth Policy creation page to your Google app in the app console under Redirect URI.

4.4.2. Authorization

In the authorization panel you have two options.

  • check user exists on platform.
  • check if user approved for Auth.

If you do not tick any of these options, it is assumed that you wish to allow any user with an authentic Google account to have access to your app.

4.4.2.1. Check User Exists on Platform

This means that if a user has an authentic Google account and the user is registered with the Platform with the id returned by Google e.g "someuser@gmail.com" then they will be authorized to access your application.

4.4.2.2. Check if User Approved For Auth

This option means that if a user has an authentic Google account and the user id returned by Google is associated with this Auth Policy then the user will be authorized to use your applications associated with this Auth Policy.

4.4.3. Adding/Removing A User From An Auth Policy

To add an existing user to your Auth Policy click the check if user is approved for Auth option. A swap select will appear populated with the users available. To add one of these users to the policy, select the user and press the arrow pointing at the approved column. To Remove a user, select the user in the approved column and click the arrow pointing at the available column.

Once you are finished configuring your Auth Policy, click the "Update Policy" button.