5 Authentication in MCS

In Oracle Mobile Cloud Service (MCS), all resources are secured and can only be accessed by authenticated users that are authorized to access those resources. As a mobile app developer, you enable one or more authentication methods in the mobile backend and then write app code to use one of these methods.

The authentication methods available are:

  • OAuth Consumer

  • HTTP Basic

  • Enterprise Single Sign-On (SSO)

    This method includes variants for browser-based SSO and use of third-party tokens.

  • Facebook Login

Before getting into the specifics of each authentication method, let’s go over how authentication relates to authorization:

  • Authentication is the process of identifying an individual, usually based on a user name and password, often in combination with other credentials such as an application key. Authentication ensures that the user is who he or she claims to be. This chapter explains how to use these features in your mobile apps.

  • Authorization is the process of determining what an individual has permission to do. After the user gains access through authentication, the system grants access according to the settings configured for the user. The MCS Mobile User Management features let you configure an intelligent authorization policy based on user roles. For an introduction to MCS Mobile User Management, see Set Up Mobile Users, Realms and Roles.

Securing Cross-Site Requests to MCS APIs

In addition to setting authentication methods, it’s very important that you manage cross-origin resource sharing (CORS) for access to MCS APIs. You do so through the Security_AllowOrigin environment policy. For browser-based applications, particularly those that use Single-Sign On (SSO) authentication, you should either not allow cross-site access at all or restrict access only to trusted origins where authorized applications are known to be hosted to mitigate vulnerability to Cross-Site Request Forgery (CSRF) attacks. If you're not using browser-based applications, it’s best to use the default value, disallow, for Security_AllowOrigin.

Control cross-site access by setting the Security_AllowOrigin environment policy value to either disallow (the default value) or to a comma separated list of URL patterns, which specifies a whitelist of trusted URLs from which cross-site requests can be made. If the origin of a cross-site request matches at least one of the patterns in the whitelist, the request is allowed.

For example, the URL value for Security_AllowOrigin might look like this:

https://myexample.com, https://*.example.com, https://*.example2.com

When specifying a URL, note the following:

  • You must include the port, unless you are using the default port for the URL scheme. For example, the pattern http://www.example.com matches the URL http://www.example.com or the URL http://www.example.com:80, but not http://www.example.com:8080.

  • When specifying values for Security_AllowOrigin, don’t include path parts and don’t include a trailing forward slash, ‘/’, character. For example, the pattern http://www.example.com/ won’t match http://www.example.com.

  • You can use an asterisk (*) as a wildcard character within a URL segment but it doesn't apply across dot (.), forward slash (/), or colon (:) characters.

    For example, if the URL is https://example.example.com:8080, the following patterns match:

    • https://*.example.com:8080

    • https://*.example.com:*

    • https://ex*.example.com:*

    These patterns, however, won’t match:

    • https://*.example.com*

    • https://example*.oracle.com:*

    These restrictions are designed to prevent matching unintended sites.

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.

OAuth Consumer Authentication in MCS

The ability to use OAuth as your authentication mechanism is built in to all mobile backends and enabled by default. Whenever you create a mobile backend, the OAuth Consumer keys are generated for you.

To enable or disable OAuth Consumer as authentication method:

  1. Open the mobile backend and select the Settings page.

  2. Under Access Keys, set the OAuth Consumer switch to ON or OFF.

For details on the access keys and environment details provided, see Mobile Backend Authentication and Connection Info.

Once you have these keys, you can use them in your apps. When using the MCS SDK for a given mobile platform, you insert these access keys in the configuration file provided by the SDK and then the SDK uses them when constructing calls to REST APIs associated with the mobile backend. If you are coding the REST calls manually, see Authenticating with OAuth in Individual REST Calls.

HTTP Basic Authentication in MCS

The ability to use HTTP Basic as your authentication mechanism is built in to all mobile backends and enabled by default.

To enable or disable HTTP Basic as authentication an method:

  1. Open the mobile backend and select the Settings page.

  2. Under Access Keys, set the HTTP Basic switch to ON or OFF.

    When switched to ON, the access keys that you need are displayed.

For details on the access keys and environment details provided, see Mobile Backend Authentication and Connection Info.

Once you have these keys, you can use them in your apps. When using the MCS SDK for a given mobile platform, you insert these access keys in the configuration file provided by the SDK and then the SDK uses them when constructing calls to REST APIs associated with the mobile backend. If you are coding the REST calls manually, see Authenticating with HTTP Basic in Individual REST Calls.

Enterprise Single Sign-On in MCS

If you want to use your own identity provider to authenticate users of your apps, you can enable Oracle Cloud’s single sign-on (SSO) capability to connect with that identity provider and then configure your mobile backends to use it. This is particularly useful if you are rolling out apps for your company’s employees and you want them to be able to sign into the apps using their existing employee login credentials. Similarly, this could work for consumer applications where the customers already have user accounts for corresponding web applications.

You can set up SSO to work in either of the following ways:

  • Browser—Based SSO through MCS. The app opens the MCS SSO URL in a browser and, after a series of redirects, displays the login screen of the remote identity provider. Once the user successfully enters their credentials, they receive an OAuth token, which you include as a bearer token on each subsequent MCS API call.

  • Third-Party SAML and JWT tokens. The app obtains a token from a trusted 3rd-party issuer, makes an API call to the MCS token exchange endpoint, and receives back an MCS-issued token, which you include as a bearer token on each subsequent MCS API call.

Enabling Browser-Based SSO through MCS

Setting up browser-based single sign-on (SSO) in MCS consists of steps both in MCS and in the Oracle Cloud My Services portal. To follow these steps, you need to have the identity domain administrator role for your Oracle Cloud account.

To set up SSO for a group of users, you need to:

  1. Create a realm in MCS for those users by following the steps at Creating Realms.

  2. Configure your Oracle Cloud identity domain to allow SSO.

    To do so, go to the Users section of the My Services portal. See Configuring Identity Management (SSO and OAuth). After SSO is set up, you may need to log out and back into MCS for it to take effect.

  3. Create user accounts in Oracle Cloud for the app users and have them assigned to the realm that you have just set up.

    These accounts correspond with the user accounts in your identity provider but only contain limited information, such as user name and email address. The password is not stored in the Oracle Cloud user account.

    To get user accounts set up, follow the instructions at Importing Groups of Mobile Users Into MCS Using Oracle Cloud.

  4. (Optional) Assign the roles to the users that they need to access the APIs. (This step assumes that the given APIs are role-based.)

    This step is not a prerequisite for developing APIs and mobile backends that use SSO as the authentication method. However, you might find it convenient to assign roles to the mobile users as they are created, especially if your team has decided on the mobile user roles to create and what users and APIs to associate them with.

    In addition, as an identity domain administrator, you can do batch assignments of roles in the My Services dashboard. Mobile app developers can use the Mobile User Management interface in MCS to assign roles, but only one at a time. This is useful for testing purposes, but might be cumbersome when setting up more than a handful of users.

Note:

If you’re not sure whether your instance of MCS is already configured to allow SSO, you can quickly check by opening the Settings page of any mobile backend, enabling OAuth Consumer authentication, and looking for the Enable SSO checkbox under the OAuth settings. If SSO isn’t configured for your identity domain, you’ll see the message SSO is not set up for your Oracle Cloud account.

Using Tokens From Third-Party Identity Providers

A remote identity provider can issue tokens that you can use to authenticate and authorize users in MCS.

MCS supports the use of tokens from third-party providers in two cases:

  • A token that identifies a SIM user. Roles are associated for the user based on information provided in Shared Identity Manager (SIM).

  • A token that identifies a virtual user. A virtual user is a user that doesn’t necessarily have a corresponding SIM record. A configured set of default roles are associated for the virtual user based either on the content in the token or by the application of a configured set of roles.

If you’re obtaining a token that identifies a user with a record in the SIM, the following conditions apply:

  • You can use either a SAML or JWT token.

  • The subject in the SAML token must identify the user’s username as defined in the SIM.

  • The sub or prn attributes in the JWT token must identify either the user’s username or email address as defined in the SIM.

If you’re obtaining a token that identifies a virtual user (a user that doesn’t have a corresponding entry in SIM), the following conditions apply:

  • You can use only SAML tokens.

  • The subject in the SAML token must specify the username that identifies the user. The subject value doesn’t need to match a SIM entry.

  • If different roles need to be assigned to different users, configure your identity provider to include the assigned role names in a specific attribute in the token.

    If your identity provider role names don’t match role names defined in MCS, you’ll have to configure mapping rules to map the token role names to the MCS role names.

Enabling SSO through Third-Party SAML and JWT Authentication Tokens

You can configure MCS to allow users to authenticate with SAML or JWT tokens provided by a third-party identity provider. Here’s how it works:

  1. You set up the app users with user accounts in Oracle Cloud or, if your users are virtual users, you set them up during the configuration of your remote identity provider.

  2. You register the third-party token issuer and one or more token certificates in MCS.

  3. You code your app to obtain a token from the third-party identity provider.

  4. The app user logs in to the app.

    When a user successfully logs in to the app, the app does the following:

    1. Retrieves a token from the third-party identity provider.

    2. Sends that token to an MCS token exchange endpoint and gets an MCS-issued token in return.

    3. Uses the MCS-token for all subsequent API calls to MCS.

You have the following possibilities:

  • Map information in the remote identity provider to MCS mobile roles to take advantage of the MCS API authorization model.

  • Use a third-party authorization token without having the remote user roles or groups (depending on the identity provider) mapped to MCS mobile roles. This option works if you only plan to use the MCS platform APIs or custom APIs that allow anonymous access.

  • Specify one or more MCS mobile roles for the identity provider to limit access to certain custom APIs to the users authenticated with this identity provider. Such users would also have access to MCS platform APIs and custom APIs that allow anonymous access (only if no other role information can be derived from the configuration or from the token content).

Configuring Third-Party SAML and JWT Token Issuers in MCS
  1. Configure your instance of MCS to use Basic Authentication.

    You can check by selecting the mobile backend in MCS and looking for HTTP Basic Authentication information under the Keys panel on the Mobile Backends landing page. If it’s not configured, open the mobile backend and turn on HTTP Basic from the Settings page.

    Note:

    Your instance of MCS doesn’t need to be configured to allow SSO, however, to test authentication through the API Test page, you’ll need to enable SSO for your mobile backend. You can check if your instance of MCS is configured for SSO from the Settings page of the mobile backend. Select the Enable Single Sign-On option if it’s not selected. If you don’t see the Enable Single Sign-On checkbox, you need to enable SSO for your Oracle Cloud account. See Configuring Identity Management (SSO and OAuth). After SSO is set up, you may need to log out and back into MCS for it to take effect.

  2. Determine whether your users are SIM users or virtual users and perform one of the following actions:

    • If the users for your app are provisioned in both the remote identity provider and in the SIM, then you can map the users identified in the token to a SIM user.

      Each SAML or JWT token is matched with a SIM user and the roles that to be associated are extracted from the SIM. Create user accounts in Oracle Cloud for the app users and have them assigned to the realm that your mobile backend uses.

      These accounts correspond with the user accounts in your identity provider but only contain limited information, such as user name, email address, and roles. The password is not stored in the Oracle Cloud user account.

      To get user accounts set up, follow the instructions at Importing Groups of Mobile Users Into MCS Using Oracle Cloud.

    • If the users aren’t provisioned in SIM, you’ll need to use the virtual users feature. The roles to be associated are derived from the contents of the SAML token, so you don’t need to set up user accounts. You’ll need to configure the token from the third-party identity provider to create a token that works with MCS. The specific steps vary per identity provider but there are some common attributes you must set. See Configuring Tokens for Virtual Users From Third-Party Identity Providers.

      You’ll also need to configure some combination of default roles, token attributes, and mapping rules. See Rules for Certificate Subject Names.

  3. (Optional) For SIM users only, assign the roles to the users that they need to access the APIs. (This step assumes that the given APIs are role-based).

    This step is not a prerequisite for developing APIs and mobile backends that use SSO as the authentication method. However, you might find it convenient to assign roles to the mobile users as they are created, especially if your team has decided on the mobile user roles to create and what users and APIs to associate them with.

    In addition, as an identity domain administrator, you can do batch assignments of roles in the My Services dashboard. Mobile app developers can use the Mobile User Management interface in MCS to assign roles, but only one at a time. This is useful for testing purposes, but might be cumbersome when setting up more than a handful of users.

  4. Add the token issuer and configure the certificate in MCS.

    1. In MCS, click open the side menu icon and select Administration from the side menu.

    2. Select an environment and click Keys & Certificates.
    3. Click the Web Service and Token Certificates tab.

    4. Click New Certificate to clear the Certificate Details and provide the following information:

      • In the Alias field, enter a unique identifiable name for the certificate.

      • In the text field, paste the definition of the token certificate that was provided by the identity provider.

    5. Click Save.

    6. Wait for the token certificate to be propagated in the system. This should take no longer than 10 minutes.

    7. Click the Token Issuer tab.

    8. Click New Issuer.

    9. Enter the name of the token issuer in the Name field under Issuer Details.

    10. Click Add (+) .

    11. From the Select Certificate Subject Names dialog, select at least one name and click Save.

      Typically the name is the subject name of the token certificate you added previously.

    12. Click Save and Close.

If you’re configuring the token for virtual users, you’ll want to create rules to determine how user name matching is applied or how token role names are mapped to MCS role names.

Configuring Tokens for Virtual Users From Third-Party Identity Providers

If you have virtual users, in general, regardless of the identity provider you use, there are some common tasks you need to perform to configure your SAML identity provider:
  1. Create the SAML2.0 app
  2. Configure the app by setting these general attributes:
    1. Set the redirect URL.
    2. Set the audience.
      SAML tokens have the concept of an audience. An audience is the intended recipient of the SAML response (the token). It restricts the set of URLs against which the token can be used. You configure the audience to the URL for the MCS token exchange endpoint. You can see an example of configuring the audience in the next section.
    3. Configure the identity provider to include an assertion that lists the applicable roles or groups for the user.
To help you get started, we’ll show you how to configure a remote identity provider to create a SAML 2.0 app that supports single sign-on. See Configuring a SAML App From OKTA.
Configuring a SAML App From OKTA

How you obtain a third party token is dependent on the remote identity provider issuing that token. Follow the instructions provided by each remote identity provider to configure the SAML 2.0 app for that identity provider. Here are the required fields that you must fill-in if you’re configuring a SAML 2.0 app from OKTA.

Assuming that you have a user role with administrator privileges in OKTA:
  1. Log in to OKTA.
  2. Click Admin.
  3. Go to the Directory tab and specify the users to have access privileges to the application:
    • Select People to specify individual users

    • Select Group to specify a group of users

      By setting a group, you can later map a group of individuals to specific MCS roles by setting Role Attribute rules in the Keys and Certificates dialog. See <xref>.

    • Select Directory Integration, then Add Active Directory to include all the users in the directory server

      or, alternatively, select LDAP to include all the users in an LDAP directory server
  4. Go to the Applications tab and click Add Application to create a new SAML 2.0 application.
  5. On the General Settings page, configure the SAML application.
    You’ll see several fields to fill in. For the token to be viable with MCS, you must fill-in the following fields:
    • Single Sign-On URL. This is the address where the SAML assertion is sent (that is , the redirect URL).

      This is the address where the response from the remote identity provider is sent. For example:

      https://hostname:####/saml

    • Audience URI. This is the intended audience of the SAML assertion. Set this value to the MCS token exchange URL.

      To exchange an externally-issued SAML token for an MCS-issued token that can be used with subsequent MCS API calls, ensure that the audience value specified in the token includes the MCS token exchange URL. The URL must include a port number, even when a default port is being used. For example:

      https://hostname:443/mobile/platform/sso/exchange-token

      You get this URL by taking the Base URL of the MCS instance and appending /mobile/plaftorm/sso/exchange-token to it. To find the Base URL, select any mobile backend on the Mobile Backends landing page in MCS and look in the Environment URL section in the mobile backend details.

    • Group Statement. Lets you add additional group attributes to the token. In this field, you can filter which groups to add. There are different types of filtering options that you can choose from. For instance, if you used a naming convention for your group names, you can set an option (Regex or Start with) to filter groups that begin with a specific prefix.

      For example, say you defined several group of users, two groups for FixItFast employees, FIF-group1 and FIF-group2, and a group for RepairItFast employees, RIF-group1. If you enter FIF* as a value, only the users in the FixItFast group are added to the token.

  6. Once you’ve configured the app, go to the Single Sign-On page.
    This is where you’ll get the token issuer name that you’ll enter into the Token Issuer panel of token issuer. See Adding Token Issuers.

    You’ll also want to get token certificate contents from this page. Paste the certificate contents in the Web Service and Token Certificates panel of the Keys and Certificates dialog when you add a token certificate. See Configuring a Web Service or Token Certificate.

If you use other third-party providers, you should be able to use the information provided here as a guide to configuring the identity provider, and obtaining the required information, such as the token issuer name and the certificate.

Obtaining Tokens From a Third-Party Provider

After you’ve configured your third party identity provider, you need a way for your app to obtain the token:

  • Log in through an embedded browser and use a web view delegate to intercept the web request that contains the token.You can use this method to obtain JWT or SAML tokens.

  • Log in through a system browser and, by way of a redirect to a registered custom URL scheme, return control to your app. You can use this method to obtain JWT tokens only. Providers of SAML tokens don’t return tokens through a redirect, so you can’t use a custom URL scheme.

Obtaining a Third-Party Token Using an Embedded Browser
If you use an embedded browser to obtain JWT or SAML third-party tokens, you’ll need to perform the following actions:
  1. Create a delegate object (for iOS) or client (for Android) to intercept the web request that contains the token. The delegate (or client) implements a method that allows your app to preview any web requests. For iOS, create a UIWebViewDelegate object. For Android, create a WebViewClient object.

  2. Register the delegate or client object with the embedded browser.

  3. Modify the method to look for a redirect URL or a form post URL, depending on how the identity provider is configured to deliver it (as either a redirect or form post). For a JWT token, you’ll use either a redirect URL or a form post. For a SAML token, only a form post can be used.

    When the specified request is located, the method should extract the token from the query string (or post body) and indicate to the browser to stop the request and close or hide the browser.

For either iOS or Android, you’ll need a web view class, a delegate (or client) class, and the delegate (or client) implementation method name.

For iOS, use the UIWebView object and the UIWebViewDelegate method:

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)
request navigationType:(UIWebVeiwNavigationType)navigationType

For Android, use the WebView client and the WebVewClient method:

public class MainActivity extends Activity {
    private  Activity mCtx;
    private static  final  String TAG = "TokenExchange";
    private String remoteIDPURL = "https://hostname/mobile/platform/sso/redirect/saml";
    private WebView myWebView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        mCtx = MainActivity.this;
        myWebView = (WebView) findViewById(R.id.webview);
        initWebView();
    }
private class MyBrowser extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error){
            handler.proceed();
        }
@Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
           if(url.contains("http://localhost:port")) {
               // get value of SAMLResponse form field
                myWebView.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByName('SAMLResponse')[0].value+'</html>');");
            }
        }
    }
class MyJavaScriptInterface
    {
        @JavascriptInterface
        @SuppressWarnings("unused")
        public void showHTML(String html){
            Log.i(TAG, "===== html is "+html);
            String samlToken = html.substring(html.indexOf("<html>") + 6,
html.indexOf("</html>"));
            Log.i(TAG, "SAML Token = " + samlToken);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    myWebView.stopLoading();
                    myWebView.setVisibility(View.INVISIBLE);
                    myWebView.destroy();
                    finish();
                }
            });
        }
    }
private void initWebView(){
        myWebView.setWebViewClient(new MyBrowser());
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new MyJavaScriptInterface(),
"HtmlViewer");
        myWebView.getSettings().setLoadWithOverviewMode(true);
        myWebView.getSettings().setUseWideViewPort(false);
        myWebView.loadUrl(remoteIDPURL);
    }
private void showMessage(final String message){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mCtx, message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

When the app is launched, it's directed to the remoteIDPURL (the redirect URL). When you enter your login credentials, the page is redirected. The onPageStarted method intercepts the response and the showHTML method retrieves the token

Obtaining a Token Using a System Browser

If you use a system browser to obtain the token, your app must relinquish control to the system browser app. When the login process is complete, you’ll need to return control to your app. You can return control via a redirect to a custom app scheme for which your app has registered. Because this procedure requires the use of a redirect URL, it works only with JWT tokens.

For either iOS or Android, you’ll need to perform the following actions:
  1. Register the custom scheme for your app as dictated by the operating system. The custom scheme URL tells the mobile OS that requests to the given scheme should be sent to your app.

  2. Edit your app to handle the redirection. You’ll need to implement a method to handle the incoming redirect, which contains the token.

Configuring Your iOS App to Obtain a JWT Token with a Custom URL Scheme

To obtain a third-party token via a system browser, you’ll need to register a custom URL scheme for your app and code your app to handle requests associated with that scheme. The scheme tells the mobile operating system to route the request to your app. The request is what contains the token.

If you’re an iOS developer, you’ll need to perform the following actions:
  1. Declare your app implements support for a custom URL scheme by editing the app’s Info.plist configuration file.

  2. Edit your app to implement the method to handle requests associated with that scheme.

To register a custom URL scheme with your iOS app, you must include the CFBundleURLTypes in your app’s Info.plist file. CFBundleURLTypes is an array of dictionaries. Each dictionary defines a URL scheme that the app supports. CFBundleURLTypes contains the following keys:

  • CFBundleURLName - a string that contains the abstract name of the URL scheme. This name should be unique. To ensure the name is unique, specify it as a reverse DNS style of identifier, such as com.company.myscheme.

    This string is also used as a key in your app’s InfoPlist.strings file. The value of the key is the human-readable scheme name.

  • CFBundleURLSchemes - An array of string s that contain the URL scheme names. For example: http, mailto, tel, and sms.

    Note:

    If multiple third-party apps register to handle the same URL scheme, there’s no way to determine which app is given the scheme.

Here’s an example: of how to implement support for the custom URL scheme:

<key>CFBundleURLTypes</key>    
<array>         
   <dict>             
       <key>CFBundleURLName</key>             
       <string>oracle.cloud.mobile.URLDemo</string>             
       <key>CFBundleURLSchemes</key>             
       <array>                 
           <string>urldemo</string>             
       </array>            
       <key>CFBundleTypeRole</key>             
      <string>Viewer</string>        
    </dict>     
</array>

This stipulates that any URL specifying the scheme, urlScheme, is redirected to your app.

When the iOS system browser encounters a URL with this custom scheme, it launches your app, if necessary, and passes the URL to your app delegate. To handle incoming URLs, your app delegate must implement the application:openURL:options: method. For example:

- (BOOL)application:(UIApplication*)application             
            openURL:(NSURL*)url             
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id>*)options 
{     
   NSLog(@"Open URL: %@", url.absoluteString);     
   NSLog(@"Open URL options: %@", options);     
   if ([url.scheme isEqualToString:@"urldemo"]) {         
      [self viewController].incomingURL = url;         
      return YES;     
   }     
   return NO; 
} 

This implementation parses the incoming URL and extracts a ‘token’ query argument and stores it in an instance variable for later use. The implementation assumes the token is passed via the URL’s query string. Your implementation might differ and the token could be stored somewhere else in the URL. After your app extracts the token from the URL, the token can be exchanged for an MCS-issued token.

If you’re not familiar with creating URL schemes or implementing them in your app, see Apple’s documentation, specifically Using URL Schemes to Communicate with Apps.

Configuring Your Android App to Obtain a JWT Token with a Custom URL Scheme

As with an iOS app, you’ll need to register a custom URL scheme for your Android app and code your app to handle requests associated with that scheme. You do this by editing the AndroidManifest.xml file:

<activity android:name=".MainActivity">
    <intent-filter>
       <action android:name="android.intent.action.VIEW"/>        
       <category android:name="android.intent.category.DEFAULT"/>
       <category android:name="android.intent.category.BROWSABLE"/>
       <data android:scheme="http"
           android:host="mytest.com"
           android:pathPrefix="/"/>
    </intent-filter>
</activity>

The following example shows how to extract the token from the custom URL scheme in the Android activity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    Uri uri = getIntent().getData();
    if(uri != null) {
        String token = uri.getQueryParameter("token");
        Logger.debug(TAG, "token is : " + token);
    }
}

When you open the link to mytest.com, you'll have the option to open the link with the app, which will launch the Android Activity from which the JWT token obtained from the custom url scheme is retrieved.

Coding Your App to Authenticate Using a SAML or JWT Token

Once you have your environment configured to trust tokens that are provided by a given third-party issuer, you can code your app to use such a token to authenticate with MCS.

  1. In the app’s login sequence, do the following:

    1. Obtain the token from the third-party token issuer. The way you can obtain the token varies by issuer.

    2. Call the MCS token exchange endpoint to exchange the third-party token for an MCS-issued OAuth token:

      • The token exchange request is a simple GET request with no parameters.

      • It must include an Authorization header of the form:

        Authorization: Bearer external-token

      • It must also include the oracle-mobile-backend-id header with the value of the Basic Auth mobile backend ID for the mobile backend that you’re using.

      The token exchange endpoint is formed by starting with the base URL for your environment (which you can get from the Settings page of a mobile backend) and appending /mobile/platform/sso/exchange-token.

  2. In all REST calls to MCS APIs, include the given token in the Authorization header.

    The header takes the form Bearer access-token.

    The access-token value includes the mobile backend ID from the original request so you don’t have to include the ID in a separate header.

Enabling Single Sign-On for a Mobile Backend

  1. Open the mobile backend and select the Settings page.
  2. Under Access Keys, make sure OAuth Consumer is enabled.
    The Enable Single Sign-On checkbox appears.
  3. Select Enable Single Sign-On.

    Note:

    If the Enable Single Sign-On checkbox does not appear, you need to enable SSO for your Oracle Cloud account. See Configuring Identity Management (SSO and OAuth).
After you enable single sign-on, an SSO token endpoint is displayed under Environment URLs. You use this token endpoint to obtain the SSO authentication token. When using the MCS SDK for a given mobile platform, you insert this token endpoint into the configuration file provided by the SDK and SDK code handles the obtaining of the token.

Adding APIs to a Mobile Backend with SSO Login

You can use any platform API or custom API in a mobile backend configured for SSO login. The platform APIs are automatically included.

To add a custom API:

  1. Click side menu icon and select Applications > Mobile Backends from the side menu.

  2. Select your mobile backend and click Open.

  3. In the left navbar of the mobile backend, select APIs.

  4. Click Select APIs.

  5. Click the + (Add) icon for the API.

Testing APIs in a Mobile Backend with SSO Login

Once you add an API to a mobile backend with SSO login enabled, you can use the API tester with SSO as the authentication method. This helps you ensure that the API call works end to end. You can test with the MCS-issued SSO token or a token from a third-party provider.

To test a custom API with SSO login:

  1. Click side menu icon and select Applications > Mobile Backends from the side menu.

  2. Select your mobile backend and click Open.

  3. In the left navbar of the mobile backend, select APIs.

  4. Click the API that you want to test.

  5. If the user that you plan to authenticate in the test has not yet been assigned the role that is needed to access the API, click the Security navigation link and switch Login Required to OFF.

  6. Click the Endpoints navigation link and scroll to the endpoint that you want to test.

  7. From the Authentication Method dropdown, select Single Sign-On Token .

  8. Obtain a valid SSO token for the mobile backend.

    If you are using web SSO, the fastest way to do this is to:

    1. Mouse over the info tip next to the Single Sign-On Token field, select the token endpoint URL that is in the info tip, and select Copy from your browser’s menu (pressing Ctrl-C might not work).

    2. Open a private or incognito browser window, paste the URL into the address bar, and press Enter.

    3. In the page that appears, enter the SSO user name and password and press Enter.

      The token should appear in the page that is returned.

  9. In the Single Sign-On Token, text field, paste the SSO token.

    If you have a token from your third-party provider, you can paste it in this field to authentication.

  10. Click Test Endpoint.

    If successful, a test response will appear with an appropriate HTTP code, such as 200.

Getting a Single Sign-On Auth Token Manually

For an app to authenticate through a single sign-on identity provider, it first needs to get an SSO OAuth token. Using the MCS SDK for your platform simplifies this process. However, if you are making the REST calls directly from your app (or you are testing API calls using another tool, such as cURL or Postman), you need to get the token manually.

  1. On the mobile backend’s Settings page, gather the following information:

    • (OAuth Consumer) Client ID

    • SSO token endpoint

  2. Form a URL that combines the SSO token endpoint and a query parameter for the client ID. For example:

    <SSO_Token_Endpoint>?clientID=<client_ID>
  3. Open a private or incognito browser window, paste the URL into the address bar, and press Enter.

    (You need to use an incognito or private window because cookies stored in your browser for whatever reason, such as from having logged in to MCS, will interfere with your SSO token request.)

  4. In the page that appears, enter the SSO user name and password and press Enter.

  5. Open a private or incognito browser window, paste the URL into the address bar, and press Enter.

    The browser window will then display your token.

    You can use this in any REST calls you make to APIs through that mobile backend.

Note:

If you want to obtain a new token, do it from a fresh incognito or private window. If you use the same window from which you previously obtained a token, the correct token might not be returned.

Getting an SSO Token Using Form Post Response Mode

If you want to use MCS’s SSO login feature with browser-based apps, you use the form post response type to get the OAuth token from the SSO token relay and have it posted back to the app through a redirect URI.

So that you don’t make yourself vulnerable to having OAuth tokens generated on your behalf and then sent to a URI out of your control, you also have to specify acceptable values for the redirect URI in the Security_SsoRedirectWhitelist environment policy.

To code the call to the SSO token relay:

  1. On the mobile backend’s Settings page, gather the following information:

    • (OAuth Consumer) Client ID

    • SSO token endpoint

  2. In your code, form a URL that combines the SSO token endpoint, a query parameter for the client ID, and a parameter for the redirect URI. For example:

    <SSO_Token_Endpoint>?clientID=<client_ID>&redirect_uri=<Redirect_URI>
  3. From your code, call that URL.

    When that URL is called, the app user is redirected to a login page where they can sign in.

To set the Security_SsoRedirectWhitelist environment policy, see Modifying an Environment Policy.

The value for the Security_SsoRedirectWhitelist environment policy is a comma-separated list of simple URL patterns. For example:

https://www.example.com, https://*.example2.com

The pattern https://www.example.com will match the URLs https://www.example.com/path1, https://www.example.com/path1/path2, and so on.

Similarly, the pattern http://www.example.com/path1 will match URLs http://www.example.com/path1, http://www.example.com/path1/path2, http://www.example.com/path1/path2/path3 and so on, but will not match URL http://www.example.com/other-path.

Here are some other rules for the environment policy value:

  • You must include the port, unless you are using the default port for the URL scheme. For example, the pattern http://www.example.com matches the URL http://www.example.com or the URL http://www.example.com:80, but not http://www.example.com:8080.

  • You can use an asterisk (*) as a wildcard character within a URL segment but it doesn't apply across dot (.), forward slash (/), or colon (:) characters.

    For example, https://example*:8080 would match https://example-source:8080, but it wouldn’t match https://example.com:8080. This restriction is designed to prevent matching unintended sites. (Imagine something like http://example.imposter.com:8080 which you would not want your wildcard to match.)

  • Simple path values don’t require a wildcard. For example, if a redirect URI of https://example.com/apps/customer is passed to the mobile backend and compared to the white list value in the above policy example, it will be accepted.

  • The protocol (https:// in the above example) must be included.

Token Expiration for SSO Login

When you use SSO as your login mode, the token expires after six hours by default, meaning that the app user will need to log in again after that time. The length of the timeout is governed by the Security_TokenExchangeTimeoutSecs policy, which is given in seconds. See Environment Policies for information on changing the policy.

Facebook Login in MCS

You can configure mobile backends to enable users to log in through Facebook. This mode of authentication is particularly useful for apps targeting consumers (as opposed to employees of your business).

When you enable users to log in to an app through Facebook, you can do the following things in the app:

  • Call any custom APIs that allow access with a social identity login.

  • In the implementation code of such custom APIs, use the custom code SDK to call MCS platform APIs (with the exception of any APIs that require enterprise roles, such as the Storage API).

  • Register for notifications.

The main steps for setting up an app to use Facebook for login are:

  1. Registering the app itself with Facebook.

  2. Configuring Facebook login in the mobile backend that the app will be using.

    Note:

    This mobile backend can only be used for Facebook login. If you wish to have apps access the mobile backend using different authentication methods, you must create a separate mobile backend for that purpose.
  3. Configuring the app itself to use Facebook for logging in.

  4. In the mobile backend, adding custom APIs that allow access through Facebook login.

Registering an App for Login Through Facebook

Before you can enable login through Facebook, you need to register your app with Facebook using the Facebook SDK for your platform. From the registration process Facebook will give you a Facebook app ID and secret which you will next configure in MCS.

For details, see Facebook’s documentation at https://developers.facebook.com/docs/apps/register.

Enabling Facebook Login in a Mobile Backend

Once you have registered your app with Facebook, you can enable Facebook login in a mobile backend.
  1. In MCS, open the mobile backend and select the Settings page.
  2. Under Social Login, switch on Facebook.
  3. In the Facebook Settings dialog, enter the app ID and app secret that you obtained when registering the app with Facebook.
  4. On the same page, make sure that HTTP Basic authentication is enabled.
    (HTTP Basic authentication is needed for the first part of the authentication process when the app requests the Facebook access token.)

Note:

If you also want to make an app accessible through any other authentication method, create a separate mobile backend for that authentication type. Then, in the configuration file provided by the MCS SDK for the given platform (e.g. OMC.plist for iOS and oracle_mobile_cloud_config.xml for Android), add the details for that mobile backend. The app can then use both mobile backends, depending on how the user authenticates.

Configuring an App to Use Facebook Login

Once you have registered your app with Facebook and have configured a mobile backend to work with Facebook login, you can configure your app to log users in with their Facebook identities. You need to:

  • Specify that Facebook is the identity provider.

  • Provide the Facebook App ID.

  • Provide the mobile backend ID and HTTP Basic anonymous key.

The easiest way to get this working is by using the MCS client SDK for the app’s platform, which enables you to specify all of the credentials in a single configuration file. See The SDKs.

Adding APIs to a Mobile Backend with Facebook Login

You can add the following types of APIs to a mobile backend configured for Facebook login.

  • Custom APIs that have the Login Required switch set to OFF.

  • Custom APIs that have the Login Required switch set to ON and the Social Login switch set to ON.

  • Any MCS platform APIs endpoints that allow anonymous access. The Analytics Collector, App Policies, Devices APIs all have endpoints that can be accessed anonymously. The Database Access API can be accessed from any custom API, including custom APIs that allow anonymous access.

To add an API to a mobile backend with Facebook login:

  1. Make sure that the API allows social login. For custom APIs, you can check by following these steps:

    1. Click side menu icon and select Applications > APIs from the side menu.

    2. Select the API that you want to add and click Open.

    3. In the API Designer, select the Security tab and check the settings.

      Note:

      APIs that you design for use with Facebook login can not be used with other authentication types. If you want an API’s functionality to be available for apps with Facebook login and apps that are based on other types of authentication (such as OAuth, enterprise SSO, or HTTP Basic anonymous access), you need separate variants of the API, each with the appropriate security settings. For more information on API security, see Security in Custom APIs.
  2. Add the API to the mobile backend:

    1. Click side menu icon and select Applications > Mobile Backends from the side menu.

    2. Select your mobile backend and click Open.

    3. In the left navbar of the mobile backend, select APIs.

    4. Click Select APIs.

    5. Click the + (Add) icon for the API.

Getting a Facebook User Access Token Manually

For an app to authenticate through Facebook, it needs to get a user access token from Facebook. Using the MCS SDK for your platform simplifies this process.

However, if you are testing an API with the API tester or another tool (such as cURL or Postman) or making the REST calls directly from your app, you need to get the user access token yourself. If you are the person who registered the app with Facebook, you can do this by following these steps:

  1. Log into your Facebook account (the one with which you registered the mobile app).

  2. Navigate to https://developers.facebook.com/tools/accesstoken/ and find your app.

  3. Click the You need to grant permissions to your app to get an access token link to generate the token. A token is generated for you on the next page.

Note:

If you anticipate testing the app over a period of several weeks, you might find it convenient to extend the validity of your access token. You can do so by clicking Extend Access Token.

For more information, see Facebook’s documentation on user access tokens at https://developers.facebook.com/docs/facebook-login/access-tokens#usertokens.

Headers Needed for API Calls with Facebook Authentication

When you call custom APIs from apps that use Facebook login, headers need to be passed to handle authentication. If you are using the the SDKs for your platform, these headers are constructed for you based on values that you have entered into the SDK’s configuration file.

If you are making REST calls to the APIs directly from your app, you need to add the following headers in your calls manually:

  • Authorization: Basic {anonymousKey}

  • Oracle-Mobile-Backend-ID: {mobileBackendID}

  • Oracle-Mobile-Social-Identity-Provider : facebook

  • Oracle-Mobile-Social-Access-Token : {YOUR_FACEBOOK_USER_ACCESS_TOKEN}

Authenticating in Individual REST Calls

When your app uses the MCS client SDK, you store the authentication credentials in one place so that you don’t need to manually insert them into each call. In addition, the SDK handles the encoding of the username and password. However, if you are making the REST calls directly from your app (or you are testing API calls using another tool, such as cURL or Postman), you need to handle the authentication in each call. The value you send in the Authorization header depends on the type of authentication.

Authenticating with OAuth in Individual REST Calls

When you have OAuth enabled as an authentication mechanism for a mobile backend, an app can authenticate itself by sending the mobile backend’s OAuth credentials (client ID and client secret) plus a user name and password to get an OAuth access token. If the API that is being called does not require a logged-in user, then the user name and password are not needed. The app then uses the OAuth token to make REST calls to APIs in the mobile backend.

You need the following information from the Settings page for the mobile backend:

  • OAuth token endpoint

  • Client ID

  • Client secret

If the API is configured to require login, you also need the user name and password for a mobile user.

To construct a REST call to authenticate via OAuth:

  1. Send the request to retrieve an access token:

    1. Base64 encode the clientID:clientSecret string.

    2. Set the Authorization header to Basic client id:client secret-Base64-encoded-string.

    3. Set the Content-Type to application/x-www-form-urlencoded; charset=utf-8.

    4. Set the request body to the appropriate grant type:

      • For access without a logged-in user, use: grant_type=client_credentials

      • For access with a logged-in user, use: grant_type=password&username=username&password=password. The user name and password must be URL encoded.

    5. POST the request to the OAuth token endpoint. For example, in cURL:

      curl -i 
      -H "Authorization: Basic clientId:clientSecret–encoded-string"
      -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8"
      -d "grant_type=client_credentials"
      --request POST oauthTokenEndpoint
  2. In the response, find the access_token property, as shown below (the value is truncated in this example).
    {"oracle_client_assertion_type":"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "expires_in":604800,
    "token_type":"Bearer",
    "oracle_tk_context":"client_assertion",
    "access_token":"eyJhbGciOiJ...FIqFiA"} 
  3. Copy the access_token property’s value into the value of the Authorization header.

    The header takes the form Bearer access_token.

Authenticating with HTTP Basic in Individual REST Calls

When you have HTTP Basic enabled as an authentication mechanism for a mobile backend, an app can authenticate itself by sending the mobile backend ID, a user name, and a password. You pass the username and password as a Base64–encoded string. If the API that is being called is set to allow anonymous access, then you pass an anonymous access key instead of a user name and password.

Remember, if your app uses the MCS mobile SDK, the authentication credentials are stored in one place so you don’t need to manually insert them.

To authenticate with MCS using HTTP Basic, you send a method to any platform endpoint with these headers:
  • Oracle-Mobile-Backend-ID: The mobile backend ID is listed on the Settings tab for the mobile backend. For details, see Mobile Backend Authentication and Connection Info.

  • Authorization: Basic: For basic authentication this header should include the mobile user’s name and password encoded in Base64 or the anonymous key. If the anonymous key is available, it will also be displayed on the Settings tab for the mobile backend.

For example:
curl -X GET
     -H "Authorization: Basic {Base64 of mobileUsername:mobileUserPassword} or {anonymousKey}" 
     -H "Oracle-Mobile-Backend-ID: {mobileBackendID}" 
                 {baseUri}/mobile/platform/users/~
The response to these calls will be one of the following:
  • In the case of 200: Success, the payload returned from MCS contains a JSON object with the user information.

  • In case of an error, a JSON error message is returned.

For more information about Base64 encoding, see Base64 Decode and Encode.

How OAuth Works in MCS

This section provides some background on how MCS takes advantage of OAuth. You don’t necessarily need to read this section to do your work, but you might find the conceptual background useful.

OAuth 2.0 is explicitly designed with REST in mind. It supports a variety of different client types that access REST APIs, including mobile apps. Secured APIs are made available only after a mobile app presents a valid OAuth access token.

Oracle Mobile Cloud Service's implementation of OAuth uses a model with the following roles:

  • Resource Owner: The resource owner is responsible for entering credentials to grant authorizations to protected resources. The resource owner is often the app user.

  • Mobile Application: The mobile app is the client that accesses protected resources and makes calls to secure APIs.

  • MCS Server: The MCS server provides the interface for accessing the protected resources.

  • OAuth Server: The OAuth server manages authorizations by the resource owner and issues access tokens. Typically, this role is also handled by the MCS server.

In OAuth 2.0, the client uses an access token issued by the OAuth server to access protected resources hosted by the MCS server.

  1. The mobile app sends credentials to the OAuth server in an HTTP header.

  2. The OAuth server returns an access token.

  3. The mobile app uses the access token to access secure MCS APIs.

This enables MCS to manage permissions and grant applications access to services without requiring a separate login for each individual service. Credentials are issued for each mobile backend. Each mobile app registered with the mobile backend uses those credentials to authenticate with any API associated with that mobile backend.

Before a mobile application can access MCS APIs, it must first register with the MCS OAuth server. The registration is typically a one-time task and can be done when the mobile backend is created. Once registered, the registration remains valid unless revoked. For details on registering a mobile app with a mobile backend, see Registering Applications.

For every custom API in Mobile Cloud Service, the mobile developer decides whether or not authentication is required. This determines which OAuth flow is used.

Resource Owner Password Credentials Grant - Authenticated Access

The resource owner password credentials grant flow is suitable for highly trusted mobile applications because the client could abuse the credentials, or they could unintentionally be disclosed to an attacker. This grant type requires direct access to user credentials, but credentials are used for a single request and are exchanged for an access token. This grant type can eliminate the need for the mobile app to store user credentials for future use, by exchanging them for a long-lived access token or refresh token.

The resource owner password credentials grant flow involves the following steps:

  1. The mobile app prompts the user (resource owner) to enter a username and password.

  2. The mobile app authenticates with the OAuth server through the token endpoint and requests an access token using the credentials entered by the user. The request contains the following parameters:

    • grant_type — Required. Must be set to password.

    • username — Required. The username of the resource owner (user).

    • password — Required. The password of the resource owner (user).

    • scope — Optional. The scope of the authorization.

  3. The OAuth server validates the credentials and issues an access token.

    • access_token

    • token_type

    • expires_in (the number of seconds before the access token is no longer valid; expiration is optional)

  4. The mobile app passes the access token to the MCS service, which validates the token and grants access.

For example, the mobile app makes the following HTTP request using transport-layer security:

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w

After the OAuth server accepts these values, it returns the following response with an access token:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
"example_parameter":"example_value"
}

Client Credentials Grant - Unauthenticated Access

The client credentials grant flow can be used when the authorization scope is limited to protected resources under the control of the mobile app. A registered trusted app is allowed to obtain an access token by providing only the client credentials to the OAuth server.

This flow is applicable in the following situations:

  • The mobile app is requesting access to protected resources under its control. For example, unauthenticated access to APIs in the Mobile Backend, such as when a mobile banking app retrieves a list of ATMs based on location.

  • The mobile app is requesting access to a protected resource where authorization has been previously arranged with the OAuth server.

The client credentials grant flow involves the following steps:

  1. The mobile app authenticates with the OAuth server through the token endpoint and requests an access token. The request contains the following parameters:

    • grant_type — Required. Must be set to client_credentials.

    • scope — Optional. The scope of the authorization.

  2. The OAuth server validates the credentials and issues an access token.

    The access token has the following parameters:

    • access_token

    • token_type

    • expires_in (the number of seconds before the access token is no longer valid; expiration is optional)

  3. The mobile app passes the access token to the service. The service accepts the token and allows access.

For example, the mobile app makes the following HTTP request using transport-layer security

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials

The OAuth server MUST authenticate the client. It returns the following response with an access token:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"example_parameter":"example_value"
}