9 Developing Mobile and Social Services Applications with the iOS Client SDK

This chapter describes how to develop Mobile and Social Services applications with the iOS Client SDK. This SDK serves as a Security Layer for developing secure mobile applications on iOS. Every native iOS app must implement this SDK to use Mobile and Social.

The iOS SDK supports devices running iOS 6.0 and above. This chapter provides the following sections:

9.1 Getting Started With the iOS Client SDK

This SDK (oamms_sdk_for_ios.zip) is included in the Oracle Access Management distribution package and can also be downloaded from the Oracle Technical Network (OTN) website.

In addition to this Developer's Guide, API documentation in HTML format is provided in the SDK. Refer to the API documentation for descriptions of API classes, interfaces, constructors, methods, and fields.

The IDM Mobile iOS Client SDK is provided as a static library. It contains the following modules:

  • Authentication Module - Processes authentication requests on behalf of users, devices, and applications.

  • Secure Storage Module - Provides APIs to store and retrieve sensitive data using the iOS Keychain feature.

  • User Role Module - Provides User Profile Services that allow users and applications to get User and Group details from a configured Identity store.

  • Cryptography Module - Provides intuitive Objective C APIs for common cryptography tasks.

  • REST Web Service Handler Module - Provides access to REST Web services protected by Access Manager.

Note:

You must have the Xcode IDE (integrated development environment) installed on an Intel-based Mac running Mac OS X Snow Leopard or later to develop applications for iOS mobile devices.

For more information, see the iOS Dev Center website:

https://developer.apple.com/devcenter/ios/index.action

9.1.1 Getting Started Using the iOS Client SDK With Xcode

Follow these steps to set up your Xcode environment.

  1. Download libIDMMobileSDK.a to your development environment and add it to Xcode.

  2. Download the PublicHeaders and PublicResources folders located in oamms_sdk_for_ios.zip.

    The PublicHeaders directory contains the IDM Mobile SDK header files.

    The PublicResources directory contains the IDM Mobile SDK resources.

  3. Add the contents of PublicHeaders and PublicResources to your project.

  4. Add the following frameworks to your project:

    • SystemConfiguration.framework

    • Security.framework

    • CoreLocation.framework

    Important:

    Before linking your project, in Build Settings add as a single line both the -ObjC and -all_load flags to "Other linker flags." Without these flags your application will crash with a "selector not recognized" runtime exception.

    Because libIDMMobileSDK.a extends pre-existing classes with categories, the linker does not know how to associate the object code of the core class implementation with the category implementation. This prevents objects created in the resulting application from responding to a selector that is defined in the category.

    For background information and steps that describe how to add flags to your project, see the following page:

    http://developer.apple.com/library/mac/#qa/qa1490/

    You can now start coding using the IDM Mobile iOS Client SDK.

    Important:

    The iOS SDK supports devices running iOS 6.0 and above.

9.2 Invoking Authentication Services With the iOS Client SDK

This section provides sample code that demonstrates how to authenticate with the Mobile and Social server. It contains sample code for the following tasks.

Refer to "Configuring Mobile and Social Services" in Oracle Fusion Middleware Administrator's Guide for Oracle Access Management for information about configuring a service provider.

9.2.1 Initializing the Required Objects

Create an NSMutableDictionary object and populate parameters:

NSMutableDictionary *sdkProps = [[NSMutableDictionary alloc] init]; 

[sdkProps setObject:OM_PROP_AUTHSERVER_OAMMS forKey:OM_PROP_AUTHSERVER_TYPE];
[sdkProps setObject:@"http://oammsurl" forKey:OM_PROP_OAMMS_URL];
[sdkProps setObject:@"myApp" forKey:OM_PROP_APPNAME];
[sdkProps setObject:@"MobileServiceDomain" forKey:OM_PROP_OAMMS_SERVICE_DOMAIN];

Next, create the OMMobileSecurityService object and pass the Dictionary object as properties.

OMMobileSecurityService *mss = [[OMMobileSecurityService alloc]                
                                           initWithProperties:sdkProps 
                                                     delegate:self]; 
 
  • The OM_PROP_OAMMS_URL property key is the URL (including protocol, host name, and port number) required to reach the Mobile and Social server. Only the HTTP and HTTPS protocols are supported.

  • The OM_PROP_APPNAME property key is a unique identifier that identifies the application. This String value must match the application "Name" value located in the Application Profile section of the Mobile and Social server administration console. For more information, see "Editing or Creating Application Profiles" in Oracle Fusion Middleware Administrator's Guide for Oracle Access Management.

  • The OM_PROP_OAMMS_SERVICE_DOMAIN property key is the name of the Service Domain in Mobile and Social server that contains the Application Profile for this application.

9.2.2 Setting Up the Service

Next, call the OMMobileSecurityService setup method.

[mss setup];

The setup method gets the configured security policies and the application profile from the Mobile and Social server. This method also gets a list of the service endpoints (the URLs) that are required for connecting to the authentication, authorization, and user profile services on the Mobile and Social server.

The setup call is an asynchronous call and on completion the iOS client SDK calls the following delegate method:

mobileSecurityService: (OMMobileSecurityService *)mobileSecurityService                         
didReceiveApplicationProfile:(NSDictionary *)applicationProfile
error:(NSError *)error;

Note:

The name of the delegate to be implemented by the application developer is OMMobileServiceDelegate.

This method returns an NSDictionary object that contains the application profile details.

Note:

The thread that calls [mss setup] must have a run loop running. If you invoke [mss setup] from a thread other than the main thread, ensure that a run loop is running in default mode.

For more information, see the iOS Developer Library Threading Programming Guide:

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html

9.2.3 Completing the Authentication Process

Upon receiving the application profile, start the authentication process. Supply your own customized login and KBA (knowledge-based authentication) views in the authentication request as in the following sample. If a customized view is not required, pass a value of zero for authnReq in startAuthenticationProcess. If a customized login views are not passed, the SDK will throw a default login and KBA view.

OMAuthenticationRequest *authnReq = [OMAuthenticationRequest alloc] init];
authnReq.kbaView = myKBAView;
authnReq.authView = myLoginView;
[[mss startAuthenticationProcess:authnReq presenterViewController:myViewController];
 

This starts the authentication process and the iOS Client SDK interacts with the Mobile and Social server to complete the authentication process. If the user is already authenticated and the authentication token is still valid, the Mobile and Social server simply returns the cached token. Otherwise, the server prompts the user to provide login credentials. If the Mobile and Social server is configured to use Knowledge Based Authentication, the iOS Client SDK automatically handles the details.

Next, the iOS Client SDK calls your delegate's didFinishAuthentication:error: method. The method returns OMAuthenticationContext, which has your token details.

Use the OMMobileSecurityService object's [mobileSecurityService authenticationContext] method to retrieve OMAuthenticatonContext at any time. This method takes a Boolean: true means check with the server to see if the authentication context is still valid; false means try to get the authentication context locally without checking whether it is still valid. For details about OMAuthenticationContext, see the API documentation.

- (void)mobileSecurityService: (OMMobileSecurityService *)mobileSecurityService
      didFinishAuthentication: (OMAuthenticationContext *)context
      error: (NSError *)error
{
  if (context == nil || error != nil)
  {
     NSString *msg = [[NSString alloc] initWithFormat:@"%@-%d: %@",
     [error domain],
     [error code], [error localizedDescription]];
     UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Err" message:msg delegate:self
                               cancelButtonTitle:@"OK" otherButtonTitles:nil];
     [alertView show];
     [msg release];
     [alertView release];
     return;
  }
 // If successful, proceed with your remaining actions. 
 // This example gets the authenticated user's attributes 
 // and presents it using User Profile Viewer.

 OMUserRoleProfileService* ups = [mss userRoleProfileService];
 OMUserManager *um = [ups getuserManager];
 OMUser *user = [um searchUser:context.userName attributes:nil shouldPreFetch:NO error:&error];
 self.user = user;
}

At this point your application can use the token obtained from the Mobile and Social server to make additional web service calls.

Note:

The OMMobileServiceDelegate now contains selectors that include mobileSecurityService. The old selectors without mobileSecurityService are also available. When both are implemented, the new selector alone is called.

9.2.4 Logging a User Out

Call the following method to log out the user:

[mss logout:false];

The Mobile and Social logout operation involves invoking a REST Web service to delete tokens maintained in the server. When the Boolean parameter clearRegistrationHandle is true, the service clears device registration handles stored in the keychain. If false, only the session tokens are deleted.

Because a web service call is involved, the following delegate is called in OMMobileServiceDelegate when the operation completes:

- (void)mobileSecurityService:(OMMobileSecurityService *)mobileSecurityService
              didFinishLogout:(NSError *)error;

sample implementation of the delegate is as follows:

- (void) mobileSecurityService:(OMMobileSecurityService *)mobileSecurityService
                   didFinishLogout:(NSError *)error
    {
        NSString *msg = nil;
        if (error)
            msg = [NSString stringWithFormat:@"%@-%05ld: %@", [error domain],
                   (long)[error code], [error localizedDescription]];
        else
            msg = [NSString stringWithFormat:@"You are logged out successfully"];
 
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Logout"
                                  message:msg
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }

Note:

The iOS Client SDK does not consume a significant amount of memory. The SDK stores registration handles, authentication handles, application profiles, and security profiles. If iOS sends a low memory warning notification, the SDK persists its cache and releases its memory. When required, the SDK can read persisted data either from a file or from KeyChainItem (covered later), as appropriate.

9.3 Setting Up URL-Based Configuration

URL-based configuration can easily configure an app utilizing the SDK. It works like this: Create an URL containing SDK configuration properties. When a user opens this URL using a mobile browser, the mobile app receives the URL in the application:openURL:sourceApplication:annotation delegate method. The mobile app needs to pass this URL to the IDM Mobile SDK. The SDK extracts and persists the configuration parameters and, once persisted, the app can reuse the configuration for subsequent authentication. This provides a user friendly way to configure the app.

The configuration URL should adhere to the following pattern:

<urlscheme>://[host]?<parameter1>::=<value1>&<parameter2>::=<value2>&...&<parameterN>::=<valueN>

For example:

wp://settings?AuthServerType::=OAMMSAuthentication&OAMMSURL::=http://host123.us.example.com:14100
&OAMMSServiceDomain::=MobileServiceDomain&ApplicationName::=WhitePages
 

The url scheme identifies the app to be opened. This can be added to an iOS project in Xcode by setting "URL Schemes" in the project Info section. Note that the URL scheme needs to match the setting in the OAM console. An URL scheme defined as wp in the console needs to be defined as wp:// in Xcode. URL schemes must be unique.

In the app, the application delegate is the right place to handle the URL and complete the configuration steps. A code sample is given below.

- (BOOL) application:(UIApplication *)application
             openURL:(NSURL *)url
   sourceApplication:(NSString *)sourceApplication
          annotation:(id)annotation
{
/* This snippet assumes "settings" is passed as host in the config URL. Replace it with the actual host passed in the config URL*/
   if([host url] isEqualToString:@"settings"])
   {
       NSSet *sdkPropsFilter = [NSSet setWithObjects:OM_PROP_AUTHSERVER_TYPE,
                                    OM_PROP_OAMMS_URL,
                                    OM_PROP_OAMMS_SERVICE_DOMAIN,
                                    OM_PROP_APPNAME,nil];
       [OMMobileSecurityService parseConfigurationURL:url
                                persistInUserDefaults:true
                                              withKey:nil
                                           andFilters:sdkPropsFilter];
   }
   return YES;
}

The mobile app can also apply some filters on the configuration received from the URL. Refer to the andFilters parameter in the code above. Using this parameter the app can specify a list of SDK parameters that should be allowed. The remaining parameters in the URL extracted from the configuration URL are ignored by the IDM Mobile SDK. After you have received and persisted the configuration, the OMMobileSecurityService object can be initialized. The withKey parameter can be used to identify a set of configuration parameters. When this is set to zero, the SDK treats it as the default configuration.

OMMobileSecurityService *mss = [[OMMobileSecurityService alloc] initWithDelegate:self];

This will create an OMMobileSecurityService object with the configuration parameters stored in NSUserDefaults. Use the following selector to pick the configuration associated with key:

- (id)initWithPropertiesAvailableInNSUserDefaultsWithKey:(NSString *)key

This helps maintain multiple configuration parameter sets in a mobile app.

9.4 About Initialization Properties for M&S Authentication

You can set the following properties when you initialize the SDK.

Table 9-1 iOS Client SDK Initialization Properties

Property Name Property Value(s) Type

OM_PROP_AUTHSERVER_TYPE

(AuthServerType)

  • OM_PROP_AUTHSERVER_OAMMS

    (OAMMSAuthentication)

NSString

Note: This is a required property.

OM_PROP_OAMMS_URL

(OAMMSURL)

An NSURL Object or a valid NSString object that can be used to create NSURL.

If you do not use this property, specify the following properties:

  • OM_PROP_OAMMS_HOST

  • OM_PROP_OAMMS_PORT

  • OM_PROP_OAMMS_PORT_IS_SSL

NSString or NSURL

OM_PROP_OAMMS_SERVICE_DOMAIN

(OAMMSServiceDomain)

Required property. Any valid Service Domain name passed as an NSString object.

NSString

OM_PROP_APPNAME

(ApplicationName)

Required property. A valid application name passed as an NSString object.

NSString

OM_PROP_OFFLINE_AUTH_ALLOWED

(OfflineAuthAllowed)

Either true or false.

This is an optional property, however, if it is not specified, offline authentication is not allowed.

The Mobile and Social server can also specify this property in the application profile. The server setting overrides the application setting.

NSString

OM_PROP_MAX_LOGIN_ATTEMPTS

(MaxLoginAttempts)

The maximum number of login attempts allowed by the user.

This is an optional property. If this property is not specified, only one login attempt is allowed.

The Mobile and Social server can also specify this property in the application profile. The server setting overrides the application setting.

NSNumber

OM_PROP_KEYCHAIN_DATA_PROTECTION

(KeychainDataProtection)

Use this property to specify the KeyChain Item protection level.

Must be one of the following values:

  • OM_KEYCHAIN_DATA_ACCESSIBLE_WHEN_UNLOCKED (KeychainDataAccessibleWhenUnlocked)

  • OM_KEYCHAIN_DATA_ACCESSIBLE_AFTER_FIRST_UNLOCK (KeychainDataAccessibleAfterFirstUnlock)

  • OM_KEYCHAIN_DATA_ACCESSIBLE_ALWAYS (KeychainDataAccessibleAlways)

  • OM_KEYCHAIN_DATA_ACCESSIBLE_WHEN_UNLOCKED_THIS_DEVICE_ONLY (KeychainDataAccessibleWhenUnlockedThisDeviceOnly)

  • OM_KEYCHAIN_DATA_ACCESSIBLE_AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY (KeychainDataAccessibleAfterFirstUnlockThisDeviceOnly)

  • OM_KEYCHAIN_DATA_ACCESSIBLE_ALWAYS_THIS_DEVICE_ONLY (KeychainDataAccessibleAlwaysThisDeviceOnly)

This is an optional property. If it is not specified, the property defaults to the highest level: OM_KEYCHAIN_DATA_ACCESSIBLE_WHEN_UNLOCKED_THIS_DEVICE_ONLY

NSString

OM_PROP_LOCATION_UPDATE_ENABLED

(LocationUpdateEnabled)

Either true or false.

This is an optional property and the default value is false. Location update consumes battery on the device and should be enabled only when required.

NSString

OM_PROP_LOCATION_UPDATE_DISTANCE_FILTER

(LocationUpdateDistanceFilter)

Location update (when enabled) is sent only when the device moves beyond the specified distance in meters.

Use this property to control the frequency of updates generated.

The Mobile and Social server can also specify this property in the Mobile Custom Attributes section with the key LocationUpdateEnabled and a numeric value. The server setting overrides the application setting. When location update is enabled and the distance filter is not set or is invalid, the default distance filter is taken as 1000m.

NSNumber

OM_PROP_AUTO_LOGIN_ALLOWED

(AutoLoginAllowed)

Either true or false.

This is an optional property, however, if it is not specified, the Auto Login feature is disabled.

NSString

OM_PROP_REMEMBER_CREDENTIALS_ALLOWED

(RememberCredentialsAllowed)

Either true or false.

This is an optional property, however, if it is not specified, the Remember Credentials feature is disabled.

NSString

OM_PROP_REMEMBER_USERNAME_ALLOWED

(RememberUsernameAllowed)

Either true or false.

This is an optional property, however, if it is not specified, the Remember User Name feature is disabled.

NSString

OM_AUTO_LOGIN_DEFAULT

(AutoLoginDefault)

Either true or false.

This is an optional property, however, if it is not specified, the default value for the Auto Login user preference is false.

NSString

OM_REMEMBER_CREDENTIALS_DEFAULT

(RememberCredentialDefault)

Either true or false.

This is an optional property, however, if it is not specified, the default value for the Remember Credentials user preference is false.

NSString

OM_REMEMBER_USERNAME_DEFAULT

(RememberUsernameDefault)

Either true or false.

This is an optional property, however, if it is not specified, the default value for the Remember User Name user preference is false.

NSString


The following OM_PROP_CRYPTO_SCHEME cryptography property is an optional property. If the application requires offline authentication and this property is not specified, the default crypto scheme is OM_PROP_CRYPTO_SSHA512.

This property can also be set using the Mobile and Social server console. Choose Custom Settings and click Mobile Custom Attributes and use the Attribute Name and Attribute Value listed in the last two columns in the table. The server setting overrides the application setting.

For information about the cryptography module included in the Mobile and Social iOS Client SDK, see Section 9.14, "Using the Cryptography Module."

Table 9-2 Cryptography Scheme Property Attributes for the iOS Client SDK

Property Value Attribute Name Attribute Value

OM_PROP_CRYPTO_SCHEME

OM_PROP_CRYPTO_PLAINTEXT

CryptoScheme

PlainText

OM_PROP_CRYPTO_AES

AES

OM_PROP_CRYPTO_SHA1

SHA-1

OM_PROP_CRYPTO_SHA224

SHA-224

OM_PROP_CRYPTO_SHA256

SHA-256

OM_PROP_CRYPTO_SHA384

SHA-384

OM_PROP_CRYPTO_SHA512

SHA-512

OM_PROP_CRYPTO_SSHA1

SaltedSHA-1

OM_PROP_CRYPTO_SSHA224

SaltedSHA-224

OM_PROP_CRYPTO_SSHA256

SaltedSHA-256

OM_PROP_CRYPTO_SSHA384

SaltedSHA-384

OM_PROP_CRYPTO_SSHA512

SaltedSHA-512


9.5 About Offline Authentication

Offline authentication is supported for the Mobile and Social authentication flow.

The OMAuthenticationRequest object that is passed to the startAuthenticationProcess:presenterViewController: method has a property called connectivityMode. This property accepts values from the enum OMConnectivityMode that is defined in the OMAuthenticationRequest.h file.

The values are described as follows.

  • OMConnectivityOnline - Always authenticates with the server. Fails if the device cannot reach the Internet.

  • OMConnectivityOffline - Authenticates locally with cached credentials. Offline authentication happens even if the device is online and can reach the server.

  • OMConnectivityAuto - Authentication happens with the server if the server is reachable. Otherwise, authentication happens offline if the device is not connected to the Internet.

Because offline authentication is part of OMAuthenticationRequest, the setting is valid for the current request alone. During offline authentication if the number of failure attempts exceeds the value of the OM_PROP_MAX_LOGIN_ATTEMPTS setting (discussed in the "About Initialization Properties for M&S Authentication" section), the locally stored credentials are wiped off and online authentication is attempted.

Note:

Offline authentication only works if the Offline Authentication" setting in the server is set to "Allowed." See "Editing or Deleting an Application Profile" in the Administrator's Guide for Oracle Access Management for more information.

9.6 Invoking Social Identity Authentication

Social Identity authentication is a feature of the Oracle Mobile and Social server that enables authentication against third party OpenId and OAuth providers like Google, Twitter, Facebook, and so on. Refer to the "Configuring Social Identity" chapter in the Administrator's Guide for Oracle Access Management for more information.

For Social Identity authentication (also known as Relying Party authentication), the SDK can be invoked using the same APIs that you use to authenticate against the Mobile and Social server. When you configure the Service Domain for authentication against the Social Identity Service, the SDK automatically follows the Relying Party authentication flow. After successful authentication, control is returned back to the app using the URL scheme configured in the Mobile and Social server.

Add this code snippet to your application in the application:openURL:sourceapplication:annotation method of the UIApplicationDelegate object to complete the flow. This helps pass the information received from the server to the SDK to signify that authentication has completed.

// Called when application in invoked via some URL
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
 
    ...
    ...
 
    NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] 
                                     initWithCapacity:1];
    [userInfo setObject:url forKey:OM_RESPONSE_URL];
 
    //Post the notification to IDM Mobile SDK
    [[NSNotificationCenter defaultCenter] 
     postNotificationName:OM_PROCESS_URL_RESPONSE
                   object:self
                 userInfo:userInfo];
 
    ...
    ...
 
    return TRUE;
}

After authentication succeeds, you can access the token from the provider (if any) with the key OM_ACCESS_TOKEN from the dictionary OMAuthenticationContext.accessTokens. If emailid is configured, it is available as OMauthenticationContext.userName.

9.7 Invoking User Profile Services With the iOS Client SDK

Before working with the code samples in this section, see "Introduction to Building Applications With User Profile Services" for notes and information that are not specific to this SDK.

The code samples in this section are organized into the following three categories:

9.7.1 Working With People

To search and retrieve user details, get the handle of OMUserManager from the OMMobileSecurityService object. See "Invoking Authentication Services With the iOS Client SDK" for information about the OMMobileSecurityService object.

OMUserManager provides synchronous and asynchronous APIs to search and get user details.

All asynchronous operations return an OMAsyncOpHandle object. You can use this object to cancel the operation before it completes. Cancelling an operation after it completes has no effect on it.

- (id)getAttribute: (NSString *)attrName returningError: (NSError **)error;
- (NSArray *)searchUsersWithFilter: (NSDictionary *)filter
                                          isSimpleSearch: (BOOL)simpleSearch
                                   attributesToBeFetched: (NSArray *)attributesToFetch
                                                pageSize: (NSInteger)pageSize
                                            pagePosition: (NSInteger)pagePosition
                                                   error: (NSError **)error;
- (OMAsyncOpHandle *)getAttributeAsynchronously: (NSString *)attrName;
- (OMAsyncOpHandle *)searchUsersAsynchronouslyWithFilter:(NSDictionary *)filter
                                          isSimpleSearch:(BOOL)simpleSearch
                                   attributesToBeFetched:(NSArray *)attributesToFetch
                                                pageSize:(NSInteger)pageSize
                                            pagePosition:(NSInteger)pagePosition;

- (OMUser *)searchUser: (NSString *)user attributes: (NSArray *)attributes
                                     shouldPreFetch: (BOOL)preFetch
                                              error: (NSError **)error;
- (OMAsyncOpHandle *)searchUserAsynchronously: (NSString *)user 
                                   attributes: (NSArray *)attributes
                               shouldPreFetch: (BOOL)preFetch
                                        error: (NSError **)error;
 
- (OMAsyncOpHandle *)searchAsynchronouslyUser: (NSString*)user
                                   attributes: (NSArray *)attributes
                               shouldPreFetch: (BOOL)preFetch;
- (NSError *)deleteUser: (NSString *)userName;
- (OMAsyncOpHandle *)deleteAsynchronouslyUser:(NSString*)userName;
- (NSError *)createUserWithAttributes: (NSDictionary *)attributes;
- (OMAsyncOpHandle *)createUserAsynchronouslyWithAttributes:(NSDictionary *)attributes;
- (OMAsyncOpHandle *)modifyAsynchronouslyUser: (NSString*)user
                                   attributes: (NSDictionary *)attributes;

9.7.2 Working With Groups

To search and retrieve group details, get the handle of OMRoleManager from OMMobileSecurityService. See "Invoking Authentication Services With the iOS Client SDK" for information about the OMMobileSecurityService object.

OMRoleManager provides synchronous and asynchronous APIs to search for groups, add members to groups, and delete members from groups.

All asynchronous operations return an OMAsyncOpHandle object. You can use this object to cancel the operation anytime before it completes. Cancelling an operation after it completes has no effect on it.

- (OMRole *)getRoleByName: (NSString *)roleName
                    error: (NSError **)error;
- (OMAsyncOpHandle *)getAsynchronouslyRoleByName: (NSString *)roleName;
- (NSError *)deleteRoleByName: (NSString *)roleName;
- (OMAsyncOpHandle *)deleteAsynchronouslyRoleByName:(NSString*)name;
- (OMUser *)getUserInfo: (NSString *)userName fromRole: (NSString *)roleName
               error: (NSError **)error;
- (OMAsyncOpHandle *)getAsynchronouslyUserInfo:(NSString *)user
                                      fromRole:(NSString *)roleName;
- (NSError *)deleteMember: (NSString *)memberName
                 fromRole: (NSString *)roleName;
- (OMAsyncOpHandle *)deleteAsynchronouslyMember:(NSString *)memberName
                                       fromRole:(NSString*)roleName;

- (OMAsyncOpHandle *)createAsynchronouslyRoleWithAttributes:(NSArray*)attributes
                                                 withValues:(NSArray*)values;
- (OMAsyncOpHandle *)modifyAsynchronouslyRole:(NSString*)role
                                   attributes:(NSArray*)attributes
                                       values:(NSArray*)values;
- (OMAsyncOpHandle *)addUserAsynchronouslyToRole:(NSString *)roleName
                                  withAttributes:(NSArray*)attributes
                                      withValues:(NSArray*)values;

9.7.3 Working With Organizations

Use the following APIs to request information about managers and their reports. They are available in OMUser.

  • Use the following APIs to get a user's manager.

    - (OMUser *)getManager: (NSError **)error;
    - (OMAsyncOpHandle *)getManagerAsynchronously;
    
  • Use the following APIs to retrieve a given user's report.

    Note:

    You need to implement a delegate to get results from the asynchronous call. For details see Chapter 9, "Using the Asynchronous API."
    - (NSArray *)getReporteesWithAttributes: (NSArray *)attributes returningError: (NSError **)error;
    - (OMAsyncOpHandle *)getReporteesAsynchronouslyWithAttributes:(NSArray *)attributes;
    

9.7.4 Using the Asynchronous API

Follow these steps to use the User Profile Service's asynchronous API:

  1. The calling class has to implement OMEntityDelegate.

  2. Implement the delegate method -didReceiveEntities:from:withAsynchronousHandle:

The following code snippet demonstrates the user search operation:

    OMUserManager *userManager = [[mss userRoleProfileService] getUserManager];
    userManager.delegate = self; //class that implements OMEntityDelegate
    [userManager searchUsersAsynchronouslyWithFilter:filter isSimpleSearch:YES attributesToBeFetched:attributes pageSize:pageSize pagePosition:pagePosition];
 
// This method receives the asynchronous operation result
-(void)didReceiveEntities:(id)entities error:(NSError *)error from:(id)omObject
       withAsynchronousHandle:(OMAsyncOpHandle *)asyncHandle

9.8 Invoking the Mobile Single Sign-on Agent App

This section describes how to use the iOS Client SDK to interact with the mobile single sign-on agent app. For conceptual information about mobile single sign-on in Mobile and Social, see the "Introducing Mobile Single Sign-on (SSO) Capabilities" and "Understanding Mobile and Social" in Oracle Fusion Middleware Administrator's Guide for Oracle Access Management.

9.8.1 Invoking the Mobile Single Sign-on Agent App From a Web Browser

Web apps can also use the single sign-on authentication features provided by the mobile SSO agent. This functionality requires Access Manager.

  1. Log on to the Oracle Access Management Administration Console.

    The Launch Pad opens.

  2. Under Access Manager click Authentication Schemes, then click the Create Authentication Scheme button.

    The "Create Authentication Scheme" tab opens.

  3. Create a new Authentication Scheme by completing the form as follows:

    • Name: MobileSSOScheme

    • Authentication Level: 2

    • Challenge Method: FORM

    • Challenge Redirect URL: /oam/server/

    • Authentication Module: LDAP

    • Challenge URL: /mobilesso?serviceDomain=MobileServiceDomain

      where MobileServiceDomain is the name of the domain that is configured for single sign-on.

    • Context Type: customWar

    • Context Value: /oic_rest

  4. In the Oracle Access Management Administration Console, do the following:

    1. Create a new Authentication Scheme in an Application Domain:

      Authentication Scheme: MobileSSOScheme

      (MobileSSOScheme is the scheme that was created in step one.)

    2. Create an HTTP Resource, for example /mobileapp, and protect the resource using the created Authentication Scheme (MobileSSOScheme). This is the URI that will be accessed from the mobile web browser (mobile Safari for iOS) and protected by a WebGate.

9.9 Authenticating Using Client Certificate

IDM Mobile SDK supports 2-way SSL mutual authentication. In addition to the client validating the identity of the server, if the authentication server is configured to perform 2-way SSL, the server will require the client certificate to validate the identity of the client. In other words, this is an additional authentication scheme where the server identifies the client, to avoid anonymous access.

Authentication based on client certificates (mutual authentication) is more secure than authentication based on the username and password method. This is because passwords do not have high entropy and it makes them vulnerable to brute force attacks. In addition, complex passwords are difficult to remember. In such a situation, client certificates are preferred as they are complex and use asymmetric cryptography to make them less vulnerable to attacks.

IDM Mobile SDK provides APIs that can be used to import PKCS12-encoded client certificates and to use these certificates to provide authentication, while making a network connection through SDK.

The following sections contain more information.

9.9.1 Importing a Client Certificate

The client certificate should be delivered at runtime to the mobile application but it can also be packaged while developing the application.

Note:

For information about how to deliver a file at runtime, see the "Registering the File Types Your App Supports" page at the following link:

https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/RegisteringtheFileTypesYourAppSupports.html

The file is placed in "Documents" directory which is only available to the application. You must call an IDM Mobile SDK API that imports the certificate to the keychain and also deletes the file.

The two following APIs for importing client certificates are available in the OMCertService class:

9.9.1.1 importClientCertificateFromFile:presenter:delegate:

This is an asynchronous API that imports the certificate and the result is delivered through a OMCertServiceDelegate protocol method.

  • fileURL is the local URL of the certificate file.

  • presenter is a UI View Controller in which IDM Mobile SDK will present its UI to collect the password.

  • delegate is the OMCertServiceDelegate object whose -(void)didImportClientCertificate:(NSArray *)certInfo error:(NSError *)error method will be called.

The certInfo object is an NSArray of NSDictionary objects, which contain information about each of the imported client identities.

9.9.1.2 importClientCertificateFromFile:password:error:

This is synchronous method that imports the certificate and returns an NSArray of NSDictionary objects. These objects will contain information about the imported client identities if the execution of the method is successful. If an error is encountered, the passed error reference is populated.

  • fileURL is the local URL of the certificate file.

  • password is the password used to decrypt the file.

  • error is the reference to a NSError object that will be populated if an error occurs while importing the certificate.

  • Return Value is the an array of certificate information returned if the import is successful, else the values is nil. No information is returned.

9.9.2 Performing Standalone Authentication

IDM Mobile SDK provides client certificate-based authentication as a separate authentication service. The following procedure describes the standalone authentication process:

  1. The following is a sample code for standalone client certificate authentication:

    NSMutableDictionary *props = [[NSMutableDictionary alloc] init];
    [props setObject:OM_PROP_AUTHSERVER_CLIENT_CERT forKey:OM_PROP_AUTHSERVER_TYPE];
    [props setObject:@"https://host:port/resource" forKey:OM_PROP_LOGIN_URL];
    [props setObject:@"ClientCertApp" forKey:OM_PROP_APPNAME];
    self.mss = [[OMMobileSecurityService alloc] initWithProperties:props delegate:self];
    [self.mss setup];
    
  2. This preceding code will initialize the SDK with client certificate authentication. There is no application profile that needs to be downloaded. However, the mobileSecurityService: didReceiveApplicationProfile:error: method of the OMMobileServiceDelegate protocol will be called. Then, the authentication process can be started using the following sample code:

    [self.mss startAuthenticationProcess:nil presenterViewController:self];
    
  3. If a client certificate challenge is received by the IDM Mobile SDK and client certificates are installed, the user will be presented with a screen where an appropriate client identity can be selected. Then, if the server accepts the client certificate, the authentication will succeed and the mobileSecurityService:didFinishAuthentication:error: method of the OMMobileServiceDelegate protocol will be called.

9.9.3 Performing Mixed Mode Authentication

Certificate-based authentication can be integrated with other authentication schemes as well. During an authentication scheme, if a client certificate challenge arises, then IDM Mobile SDK will present the list of installed certificates to the user. The user must choose a certificate, after which the authentication will proceed according to the authentication scheme. To ensure that the client certificate authentication option is present with other authentication schemes, the following additional property must be added while initializing the SDK:

[props setObject:@"TRUE" forKey:OM_PROP_PRESENT_CLIENT_IDENTITY_ON_DEMAND];

The default value of this property is false.

9.10 Understanding and Using OAuth2.0 for iOS SDK

The IDM Mobile SDK provides for authorization with the OAM (M&S) OAuth Server to access protected resources. The SDK will also work with any OAuth2.0 generic server, if it supports the grant types mentioned in Section 9.10.1.1.2, "Access Token Retrieval" for mobile clients.

After initializing the IDM Mobile SDK with the correct properties and after authentication, the application must be able to get the access tokens.

The following is a list of new properties that have been added for OAuth2.0:

Configuration Property Valid Value Mandatory
OM_PROP_AUTHSERVER_TYPE

(AuthServerType)

String Constant

OM_PROP_OAUTH_OAUTH20_SERVER

Yes
OM_PROP_OAUTH_AUTHORIZATION_GRANT

(OAuthAuthZGrantType)

String Constant

OM_OAUTH_AUTHORIZATION_CODE

OM_OAUTH_IMPLICIT

OM_OAUTH_RESOURCE_OWNER

OM_OAUTH_CLIENT_CREDENTIALS

OM_OAUTH_ASSERTION

OM_OAUTH_OAM_CREDENTIAL

Yes
OM_PROP_OAUTH_AUTHORIZATION_ENDPOINT

(OAuthAuthZEndpoint)

NSString Yes
OM_PROP_OAUTH_TOKEN_ENDPOINT

(OAuthTokenEndpoint)

NSString Mandatory if the OM_PROP_OAUTH_AUTHORIZATION_GRANT is AUTHORIZATION_CODE
OM_PROP_OAUTH_REDIRECT_ENDPOINT

(OAuthRedirectEndpoint)

NSString Yes
OM_PROP_OAUTH_CLIENT_ID

(OAuthClientID)

NSString Yes
OM_PROP_OAUTH_SCOPE

(OAuthScope(s))

NSSet Yes
OM_PROP_BROWSER_MODE

(BrowserMode)

OM_PROP_BROWSERMODE_EMBEDDED

or

OM_PROP_BROWSERMODE_EXTERNAL

No

However, the default will be set to EXTERNAL, if a value is not set during initialization.

OM_PROP_OAUTH_CLIENT_SECRET

(OAuthClientSecret)

NSString No
OM_PROP_OAM_OAUTH_SERVICE_ENDPOINT

(OAMOAuthServiceEndpoint)

NSString No

Note: This is only required for OAM OAuth mobile clients

OM_PROP_OAUTH_ASSERTION_JWT (OAuthUserJWTAssertionValue) NSString No
OM_PROP_OAUTH_ASSERTION_SAML2 (OAuthUserSAML2UserAssertionValue) NSString No
OM_PROP_OAUTH_CLIENT_ASSERTION_SAML2 (OAuthClientSAML2AssertionValue) NSString No
OM_PROP_OAUTH_CLIENT_ASSERTION_JWT (OAuthClientJWTAssertionValue) NSString No

9.10.1 OAM Mobile and Social (M&S) OAuth

The OAM M&S server supports the following OAuth clients, which can be used with mobiles.

  • Web Clients: These clients can use the IDM Mobile SDK with the OAuth Generic flows as discussed below. The web-based clients are considered as trusted clients and possess a client secret. Therefore, the authorization server knows the identity of the client that is making the request. When using this client type, the application should pass the client secret during SDK initialization.

  • Mobile Clients: Mobile clients are not considered to be confidential clients and hence, these clients do not posses any client secret. The OAM OAuth server provides a way by which the mobile clients can register, by sending the device claims along with username and password of the end user. This flow is proprietary to the OAM OAuth server. After dynamic client registration is performed, the IDM Mobile SDK receives a client assertion and a user assertion (if the "SERVER SIDE SSO" is disabled). The client assertion is required to be sent in all the subsequent requests for access token acquisition or for other token operations. IDM Mobile SDK manages the life cycle of the client assertion and does not return this to the client application.

New Token Type Significance
Client Assertion This token is generated after the dynamic client registration is done. This token must be sent in every request made to the authorization server. The server identifies the request or client from the client assertion and it validates the same. Client assertions are usually JWT tokens.
User Assertion Since dynamic client registration involves user authentication, M&S along with client assertions generates a user assertion. This user assertion marks the user session at the server side. The user assertion is returned by the server only when the SERVER SIDE SSO is disabled.

The client or SDK can thus use the same assertion for acquiring the access token for resource access every time, till the user session is valid at the server.

Also when the SERVER SIDE SSO is enabled, the SDK or client can still use the user assertion by adding the following parameter in every request:

use_server_side_device_store = true


9.10.1.1 Authentication

After the setup is done, application can now perform authentication which in this case is to get an access token for accessing the OAuth protected resources. The authentication flow is not different from the other flows.

In iOS, the OMMobileSecurityService's startAuthenticationProcess:nil presenterViewController:presenter is used to initiate the authentication process. After completing, the SDK calls back (void)mobileSecurityService: (OMMobileSecurityService *)mobileSecurityServicedidFinishAuthentication: (OMAuthenticationContext *)contexterror: (NSError *)error of OMMobileServiceDelegate.

If the authentication is successful the context will contain the access token along with the other axillary tokens like user_assertion if available. Also, if the authentication was not successful the authentication context will be null.

This flow Authentication involves the following steps:

9.10.1.1.1 Dynamic Client Registration

Mobile clients are usually not considered to be confidential hence server does not create any secrets for these clients. However, OAM M&S server provides a way by which the client can register itself dynamically to get a client token (client_assertion) which is tied to the user and the device from which the registration is taking place. The device info is useful for the server in order to track the user and the device so that it can trigger it OAAM plugin if applicable. For more information refer to the server side documentation in Oracle Fusion Middleware Administrator's Guide for Oracle Access Management.

OAM M&S supports two ways of performing client registration: 2-legged client registration and 3-legged client registration. The client registration flow is decided by the SDK based on the grant type provided by the application during initialization. The property used to define the grant type is OM_PROP_OAUTH_AUTHORIZATION_GRANT_TYPE.

  • 2-Legged Client Registration: This is done when the grant type is either RESOURCE_OWNER or ASSERTION or CLIENT_CREDENTIALS or OAM_CREDENTIALS. After end of this flow SDK gets the client_assertion along with user assertion token.

    Note:

    The availability of user_assertion on the client side is dependant on the value that is set for the SERVER_SIDE_SSO property in the server.
  • 3-Legged Client Registration: This is done when the grant type is AUTHORIZATION_CODE. This flow will invoke the external or embedded browser based on the initialization property. Usually after end of this flow IDM Mobile SDK gets only the client_assertion token.

9.10.1.1.2 Access Token Retrieval

After the dynamic client registration is done and the SDK has a valid client_assertion token it can proceed with the access token acquisition flow. The access token can be acquired using the grant type specified using the initialization property OM_PROP_OAUTH_AUTHORIZATION_GRANT. Table 9-3 contains information on the grant types and the appropriate property value for each.

Table 9-3 Grant Types for Getting the Access Token

Grant Type Initialization Property Value Notes

OAM Credential Grant Type

The value of the initialization property should be OM_OAUTH_OAM_CREDENTIAL.

In 2-legged client registration flow, the SDK will obtain a client_assertion and a user_assertion token based on the value set for the SERVER_SIDE_SSO property. To complete the authentication flows, SDK will first exchange the client_assertion to get the access token for OAuth protected resources, and then use the client_assertion and user_assertion (if available) to get the OAM_ID(USERTOKEN_MT) and OBSSOCookie(USERTOKEN) tokens. This grant type is provided by the server for the clients who use the OAM_ID cookie to access the webgate protected resources.

Resource Owner Grant Type

The value of the initialization property should be OM_OAUTH_RESOURCE_OWNER.

2-legged client registration is performed. The SDK collects the user name and password in order to complete the 2-legged client registration. Hence the SDK will reuse these user credentials to get the access token. The SDK does not honor the SERVER_SIDE_SSO property sent by the server in this flow and will always send the user credentials to get an access token. If the client assertion is expired or invalidated, the SDK will again ask for the end user credentials to first renew the client assertion and then get the access token.

Client Credentials Grant Type

The value of the initialization property should be OM_OAUTH_CLIENT_CREDENTIALS.

2-legged client registration is performed. To complete the authentication flow, the SDK uses the client_assertion obtained after client registration to get the access token. If the client assertion is expired or invalidated, the SDK will ask for the end user credentials to first renew the client assertion and then get the access token.

Assertion Grant Type

The value of the initialization property should be OM_OAUTH_ASSERTION.

In 2-legged client registration flow, the SDK gets a client_assertion token and a user_assertion token. The user_assertion token is made available by server only if the SERVER_SIDE_SSO is false. To complete the authentication flow the SDK uses the user assertion obtained after client registration to get the access token. This grant type honors the SERVER_SIDE_SSO configuration property from the server by appropriately forming the request based on the property value. If the SERVER_SIDE_SSO property is set to true, the SDK adds the oracle_use_server_device_store=true parameter in the access token request. In doing so, it requires the server to reuse the user session that was created at the server side. Also if oracle_use_server_device_store=true, then the client does not need to send the user assertion every time.

Applications can provide custom assertions for this flow using the initialization property OM_PROP_OAUTH_ASSERTION_JWT for JWT assertion and OM_PROP_OAUTH_ASSERTION_SAML2 for SAML2 assertions. The SDK will use this assertion for access token acquisition to complete the authentication flow.

Authorization Code Grant Type

The value of the initialization property should be OM_OAUTH_AUTHORIZATION_CODE.

Involves the 3-legged client registration flow in which the SDK receives only the client_assertion. During this flow, the SDK invokes either the external or embedded browser based on the initialization property OM_PROP_BROWSER_MODE. The SDK must invoke the browser twice to complete the authentication flow. The first time is for client registration and the second time is for getting the access token.

NOTE: If the application provides the value as BrowserMode.EXTERNAL for the OM_PROP_BROWSER_MODE property, the user may not have to enter the credentials twice in the external browser. This is because the server will set the OAM_ID cookie in the external browser during client registration flow itself, and so, during the access token acquisition the browser will not prompt for the login credentials.


9.10.2 Standard Flows (Generic Implementation)

Note:

Client secret has to be supplied for confidential clients.

IDM Mobile SDK supports authorization against any OAuth2.0 compliant server. The Current implementation supports the following grant types:

  • Implicit grant type. (The "client id" and "authorization endpoint" are required)

  • Authorization code grant type. (The "client_id," "authorization end point," and "token endpoint" are required)

  • Resource Owner grant type. (The "client_id" and "token end point" are required)

  • Client Credentials. (The "client_id" and "client_secret" are required)

  • Assertion. (The application must provide an assertion value using either the OM_PROP_OAUTH_ASSERTION_JWT or OM_PROP_OAUTH_ASSERTION_SAML2 property, based on the type of assertion)

9.10.2.1 Authentication Scopes

The SDK accepts a list of scopes to authenticate the user (get a valid access token) with the OAuth2.0 server.

After the authentication of the user and user consent with the Authorization server, the access token returned by the Authorization server is retrieved by the IDM Mobile SDK and is associated initially with the given scopes.

So, before the start of any authentication process, the SDK checks for the availability of any valid access token for the scopes asked in request. If matching access tokens exist or if they are wider than the requested scopes, then the SDK will not authenticate again. It will instead return the same authentication context or access token.

The IDMMobile SDK provides the ability to refresh the access token if it is supported by the authorization server. The life cycle of an access token is controlled by the SDK. The SDK provides the API to get the access token for passed scopes, and the ability to refresh it if required.

The following is the sample code for initialization:

                    NSMutableDictionary  *sdkProps = [[NSMutableDictionary alloc] init];
        [sdkProps setObject:OM_PROP_OAUTH_OAUTH20_SERVER                     forKey:OM_PROP_AUTHSERVER_TYPE];
        [sdkProps setObject:@"<Token Endpoint>"                     forKey:OM_PROP_OAUTH_TOKEN_ENDPOINT];
        [sdkProps setObject:@"<Authorization Endpoint>"                     forKey:OM_PROP_OAUTH_AUTHORIZATION_ENDPOINT];
        [sdkProps setObject:@"<Client ID>"                     forKey:OM_PROP_OAUTH_CLIENT_ID];
        [sdkProps setObject:OM_OAUTH_AUTHORIZATION_CODE                     forKey:OM_PROP_OAUTH_AUTHORIZATION_GRANT];/*The value could be any of the grant type supported by SDK*/
        [sdkProps setObject:@"<Registered Redirect URL>"                     forKey:OM_PROP_OAUTH_REDIRECT_ENDPOINT];
        [sdkProps setObject:OM_PROP_BROWSERMODE_EXTERNAL                     forKey:OM_PROP_BROWSERMODE];
         NSMutableArray *scope = [[NSMutableArray alloc] init];
[scope addObject:@"<OAuth Scope>"];
[sdkProps setObject:[NSSet setWithArray:scope] forKey:OM_PROP_OAUTH_SCOPE];         OMMobileSecurityService *mss = nil;
        mss = [[OMMobileSecurityService alloc] initWithProperties:sdkProps                                                           delegate:self];
        self.mss = mss; /*Please note that initialized SDK object need to be retained atleast till the authentication completes.*/

If the initialization process is successful, an Object for OMMobileSecurityService will be returned. A nil return value signifies that there are some invalid configuration parameters. You must reconfigure the parameters and retry the initialization process.

After initialization, you must set up the SDK. To do so, use the following API:

[self.mss setup];

The SDK will download the M&S mobile client in the setup call. This is an asynchronous API.

After the setup completes, you must call the startAuthenticationProcess:presenterViewController API on the mss object to start the OAuth flow.

A list of scopes can be passed to this API as part of OMAuthenticationRequest object. If passed, these scopes will override the ones passed during the following operation:

        OMAuthenticationRequest *req = [[OMAuthenticationRequest alloc] init];
 
        NSMutableArray *scope = [[NSMutableArray alloc] init];
 
        [scope addObject:@"<OAuth Scope>"];
 
        req.oauthScope = [NSSet setWithArray:scope];
 
        [scope release];
 
        NSError *error = [self.mss startAuthenticationProcess:req presenterViewController:self];

Note:

The application must implement the didFinishAuthentication: delegate method of OMMobileSecurityServiceDelegate, to retrieve control after authentication.

The following is the sample code for M&S mobile client initialization:

 NSMutableDictionary *sdkProps = [[NSMutableDictionary alloc] init];
 
[sdkProps setObject:OM_PROP_OAUTH_OAUTH20_SERVER
 
forKey:OM_PROP_AUTHSERVER_TYPE];
 
[sdkProps setObject:@"<M&S servers service endpoint for the desired OAuth service profile>"
 
forKey:OM_PROP_OAUTH_OAM_SERVICE_ENDPOINT];
 
[sdkProps setObject:@"<Mobile Client ID>"
 
forKey:OM_PROP_OAUTH_CLIENT_ID];
 
[sdkProps setObject:OM_OAUTH_RESOURCE_OWNER
 
forKey:OM_PROP_OAUTH_AUTHORIZATION_GRANT_TYPE];
 
NSMutableArray *scope = [[NSMutableArray alloc] init];
 
[scope addObject:@"<OAuth Scope>"];
 
[sdkProps setObject:[NSSet setWithArray:scope] forKey:OM_PROP_OAUTH_SCOPE]; 

9.10.3 New APIs

The three following API's have been added to OMAuthenticationContext class:

  • -(BOOL)isValidForScopes:(NSSet *)scopes refresh:(BOOL)refresh:

    This API takes a set of scopes and a bool to refresh, if a refresh token exists for a matching token.

  • -(NSArray *)accessTokensForScopes:(NSSet *)scopes:

    This API takes a set of scopes and return all valid tokens which are tied to that set of scopes. If nil is passed as scope, then all valid access tokens are returned.

    Note:

    The OAuth tokens are present in an NSArray (named tokens), in the OMAuthenticationContext object.
  • -(void)checkValidityAsynchronouslyForScopes:(NSSet*)scopes andRefreshExpiredTokens:(BOOL)refresh:

    This API takes a set of scopes and a bool to refresh, if a refresh token exists for a matching token. It is an "async call" which will tell if a valid token exists for passed scopes. This API will try to refresh an expired token if the value for refreshExpiredToken is set to true. An application developer must implement the OMAuthenticationContextDelegate method to get the delegate callback.

Sample Code:

- (void)checkAuthContextValidity{      self.authContext.delegate = self; //This delegate needs to be set before calling the async API
      NSMutableArray *scope = [[NSMutableArray alloc] init];
     [scope addObject:@"UserProfile.users"];
     [self.authContext checkValidityAsynchronouslyForScopes:[NSSet setWithArray:scope] andRefreshExpiredTokens:YES];
}
//This is the OMAuthenticationDelegate method which needs to be implemented for getting the async API callback
- (void)authenticationContext:(OMAuthenticationContext *)authenticationContext
          didFinishValidation:(BOOL)valid
     forMobileSecurityService:(OMMobileSecurityService *)mobileSecurityService
                     andError:(NSError *)error
{
    if(valid)
    {
          NSMutableArray *scope = [[NSMutableArray alloc] init];
         [scope addObject:@"UserProfile.users"];
         NSArray *token = [authenticationContext tokensForScopes:[NSSet setWithArray:scope]]; //This token can be used for subsequent //requests
    }
    else
    {
         [mobileSecurityService startAuthenticationProcess:nil presenterViewController:self]; //If no valid token exists for passed scopes                                                                                                      //authentication can be started
    }
}

9.10.4 Using the External Browser

If the delegate is not implemented, you must implement it using the following snippet of sample code:

application:openURL:sourceApplication:annotation method of UIApplicationDelgate :
        NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithCapacity:1];
        [userInfo setObject:url forKey:OM_RESPONSE_URL];
        //Post the notification to IDM Mobile SDK
        [[NSNotificationCenter defaultCenter] postNotificationName:OM_PROCESS_URL_RESPONSE
                                                            object:self
                                                          userInfo:userInfo];

        [userInfo release];

9.10.5 Accessing Protected Resources

Use the following API in the OMRESTRequest request to insert Access Tokens in a header before accessing an OAuth Protected resource:

- (OMAsyncOpHandle *)executeRESTRequestAsynchronously: (NSMutableURLRequest *)request
 
                                            forScopes: (NSSet *)scopes
 
                                    convertDataToJSON: (BOOL)isJsonRepresentation
 

This API executes the given REST request asynchronously, after adding access tokens to header for given scopes, and returns a handle to the asynchronous operation. The caller can abort the asynchronous request using this handle at any time before the request is completed. The REST request is executed in a separate thread and the result is returned through the OMRESTRequestDelegate delegate. The following flows are supported in OAuth SIM v3.1:

  • Client_credentials flow with id & secret

  • Client_credentials flow with JWT Bearer Token signed with Client's private key

  • Resource owner password flow with client id & secret and resource owner password

  • Resource owner password flow with JWT Bearer Token signed with Client's private key and resource owner password

  • Jwt-bearer(OM_OAUTH_ASSERTION) flow with Client JWT Token and User JWT Token signed using the Client's private Key

  • Jwt-bearer(OM_OAUTH_ASSERTION) flow with Client JWT Token and User JWT Token Issued by SIM Server

The following sections have some details.

9.10.5.1 Initializing the SDK for Identity Domain Header Injection

The following property needs to be set while initializing the SDK for Identity domain header Injection:

  • OM_PROP_IDENTITY_DOMAIN_NAME

    The value of this parameter should contain Identity Domain name

  • OM_PROP_IDENTITY_DOMAIN_NAME_IN_HEADER

    This property is introduced to maintain backward compatibility as till now SDK used to prefix identity domain with username. Pass true for this property if identity domain needs to be passed in header.

9.10.5.2 Initializing the SDK for Client Token

The following property needs to be set while initializing the SDK for Client token:

  • OM_PROP_OAUTH_CLIENT_ASSERTION_JWT

    It should contain value for Client JWT token

  • OM_PROP_OAUTH_CLIENT_ASSERTION_SAML2

    It should contain value for Client SAML2 token. However, the SIM server only supports JWT Token currently, so this property can be ignored.

9.10.5.3 Initializing the SDK for User Token

The following property needs to be set while initializing the SDK for User token:

  • OM_PROP_OAUTH_ASSERTION_JWT It should contain value for User JWT token.

  • OM_PROP_OAUTH_ASSERTION_SAML2

    It should contain value for User SAML2 token. However, the SIM server only supports JWT Token currently, so this property can be ignored.

The following is the sample code for Android for SIMv3.1:

Note:

Read the comments corresponding to each property in the sample code and only the property names which are required for the application usage must be passed during SDK initialization. Apart from the initialization properties, every thing else remains same i.e. authenticate , isValid, logout.
    private Map<String, Object> getConfigMapForSIMv31() {
        Map<String, Object> configMap = new HashMap<String, Object>();
        configMap
                .put(OMMobileSecurityService.OM_PROP_APPNAME, "DemoSIMv3.1App");
        configMap.put(OMMobileSecurityService.OM_PROP_AUTHSERVER_TYPE,
                AuthServerType.OAuth20);
        configMap.put(OMMobileSecurityService.OM_PROP_OAUTH_CLIENT_ID,
                "client_id");
        configMap.put(OMMobileSecurityService.OM_PROP_OAUTH_CLIENT_SECRET,
                "client_secret");
        configMap.put(OMMobileSecurityService.OM_PROP_OAUTH_TOKEN_ENDPOINT,
                "http://www.example.com:1234/token_endpoint");\\
        configMap.put(
                OMMobileSecurityService.OM_PROP_OAUTH_AUTHORIZATION_ENDPOINT,
                "http://www.example.com:1234/authz_endpoint");\\
        configMap
                .put(OMMobileSecurityService.OM_PROP_REMEMBER_USERNAME_ALLOWED,
                        true);
        configMap.put(
                OMMobileSecurityService.OM_PROP_OAUTH_AUTHORIZATION_GRANT_TYPE,
                OAuthAuthorizationGrantType.RESOURCE_OWNER);
 
        configMap.put(OMMobileSecurityService.OM_PROP_IDENTITY_DOMAIN_NAME,
                "DemoTenant");// If this is supplied then the SDK will not
                                // expect the idenity domain to be collected
                                // from user or from the authentcationRequest
                                // object. Instead use the same identity domain passed during init. 
        configMap.put(
                OMMobileSecurityService.OM_PROP_IDENTITY_DOMAIN_NAME_IN_HEADER,
                true);// This property is required if the application wants the
                        // SDK to send the identity domain as the header.
 
 
        configMap.put(OMMobileSecurityService.OM_PROP_OAUTH_ASSERTION_JWT,
                "user assertion");// required when the application wants to use
                                    // assertion as a grant type.
        // configMap
        configMap.put(OMMobileSecurityService.OM_PROP_LOGOUT_URL,
                TesterAppConstants.OAUTH_LOGOUT_URL);
        configMap
                .put(OMMobileSecurityService.OM_PROP_SESSION_ACTIVE_ON_RESTART,
                        true);// required if the application wants the SDK to
                                // persist the authentication context, The
                                // default behavior is not to persist the
                                // authentication context thus forcing re
                                // authentication on application restart.
        configMap.put(OMMobileSecurityService.OM_PROP_OAUTH_REDIRECT_ENDPOINT,
                "myredirecturl://");
        String scope = "scope1,scope2,scope3";
        Set<String> scopeset = new HashSet<String>();
        if (!TextUtils.isEmpty(scope)) {
            String[] scopes = scope.split(",");
            for (String s : scopes) {
                scopeset.add(s);
            }
        }
        if (!scopeset.isEmpty())
            configMap
                    .put(OMMobileSecurityService.OM_PROP_OAUTH_SCOPE, scopeset);
        configMap
                .put(OMMobileSecurityService.OM_PROP_REMEMBER_USERNAME_ALLOWED,
                        true);
        configMap.put(OMMobileSecurityService.OM_PROP_OFFLINE_AUTH_ALLOWED,
                true);
        configMap.put(OMMobileSecurityService.OM_PROP_BROWSER_MODE,
                TesterAppConstants.OAUTH_BROWSER_MODE);
 
        return configMap;
    }

9.10.6 Credential Collection

For the IMPLICIT and AUTHORIZATION_CODE grant types, the SDK invokes an external or embedded browser. The authorization server will load the login page in the browser and so, the end user submits the login credentials directly to the authorization server.For the RESOURCE_OWNER, CLIENT_CREDENTIALS, ASSERTION, and OAM_CREDENTIAL grant types, the SDK will provide a native UI to collect the login credentials of the end user by default. However, the application can direct the SDK to provide a custom view or UI for credential collection. Refer to Section 9.13, "Login and KBA View Customization" for more information.

Note:

Only the "remember user name flag" can be used with OAuth2.0 because the resource owner grant type SDK collects the credentials. Refer to Section 9.16, "Using the Credential Store Service (KeyChain)" for more information.

9.11 Invoking REST Web Services

You can use the Mobile and Social SDK to authenticate against Access Manager using the Mobile and Social service. After authenticating against Access Manager, the SDK gets a token and persists it in the cookie store so that any Access Manager protected app can use the embedded web browser. Access Manager protected REST web services, however, cannot be accessed using the web browser.

The Mobile and Social SDK provides the OMRESTRequest class to access REST web services protected by Access Manager. First, use the SDK to authenticate against the OAM server using Mobile and Social services.

Next, initialize the OMRESTRequest object by passing a OMMobileSecurityService object and a delegate object. You can use either of the following methods:

executeRESTRequest: convertDataToJSON: isJsonRepresentation returningResponse: error:  

- or -

executeRESTRequestAsynchronously: convertDataToJSON:

The former is a synchronous call and the latter is an asynchronous call. The asynchronous call returns the result through the following OMRESTRequestDelegate method:

didFinishExecutingRESTRequest: data: urlResponse: error: asyncHandle:

The following example demonstrates the asynchronous API of the OMRESTRequest object.

- (void)someMethod
{
    OMMobileSecurityService *mss = ...;
    ...
    //Initialize OMRESTRequest object. In this example, instead of using
    //"initWithMobileSecurityService: delegate:" method, we use init method
    //and set the properties
    OMRESTRequest *restReq = [[OMRESTRequest alloc] init];
    restReq.delegate = self;
    restReq.mobileService = mss;

    NSURL *url = [[NSURL alloc] initWithString:@"http://myresturl.example.com/resturl"];
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:1];

    // It is important to set the User-Agent to the values configured in the OAM 11g R2
    // WebGate user defined parameters.
    // We need to configure OAM 11g R2 WebGate with these parameters:    //  i) OAMAuthUserAgentPrefix=<Prefix for User-Agent HTTP header> (Example: OIC)    // ii) OAMAuthAuthenticationServiceLocation=<OIC Server URL> (Example:
    //     http://host123.us.example.com:14100/oic_rest/rest/mobileoamauthentication)
    [dictionary setObject:@"OAMMS-Agent" forKey:@"User-Agent"];
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    [urlRequest setAllHTTPHeaderFields:dictionary];
    [url release];
    [dictionary release];
    [urlRequest setHTTPMethod:@"GET"];
    OMAsyncOpHandle *opHandle = [restReq executeRESTRequestAsynchronously:urlRequest
                                                        convertDataToJSON:FALSE];
    [urlRequest release];
    OMLog(@"%@", opHandle);
}

-(void) didFinishExecutingRESTRequest:(OMRESTRequest *)RESTRequest
                                 data:(id)data
                          urlResponse:(NSURLResponse *)urlResponse
                                error:(NSError *)error
                          asyncHandle:(OMAsyncOpHandle *)handle
{
    if (error)
    {
        //In case of error, show the error message
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"REST Request Error"
                                                            message:[error localizedDescription]
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    else
    {
        //Show the result in the UIAlertView
        NSString *disp = nil;
        if ([data isKindOfClass:[NSDictionary class]])
        {
            NSDictionary *dict = (NSDictionary *)data;
            disp = [[dict OMJSONRepresentation] retain];
        }
        else
        {
            disp = [[NSString alloc] initWithData:data
                                         encoding:NSASCIIStringEncoding];
        }
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Received"
                                                            message:disp
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [disp release];
        [alertView show];
        [alertView release];
    }
}

Note:

OMRESTRequest can obtain the required token from Access Manager only if the REST web service is protected using an Oracle Access Management 11g R2 WebGate.

The user defined parameter of the Access Management 11g R2 WebGate must contain the OAMAuthUserAgentPrefix and OAMAuthAuthenticationServiceLocation properties. The same property values must be specified by the mobile application in its header.

OMRESTRequest can be initialized without OMMobileSecurityService, as well. In such cases, the OMRESTRequest APIs will just return the URL values.

9.11.1 Understanding the OMRESTRequest API Flow

The following steps describe the internal flow of the OMRESTRequest API:

1. The OMRESTRequest API invokes the URL provided by the mobile application.

2. The Oracle Access Management 11g R2 WebGate returns a 401 error with the following details:

   HTTP/1.1 401 Authorization Required
   WWW-Authenticate: OAM-Auth realm="<WebGateName>:<AuthenticationLevel>
   <RelativeRESTURL>", request-ctx="<RequestContext>"
   

3. The Mobile and Social SDK maintains a cache of Access Tokens that it has obtained during the application's lifetime. If the Access Token for this WebGate is already present in the cache, the SDK injects the Access Token into the application request.

4. If an Access Token for the WebGate is not available in the Mobile and Social SDK cache, it sends a REST request to the Mobile and Social server to obtain the Access Token for the WebGate.

5. If the request is valid, Mobile and Social returns an Access Token in the response.

6. The Mobile and Social SDK injects the token returned by the Mobile and Social server.

9.12 Using the iOS SDK to Create a Custom Mobile Single Sign-on Agent App

This section contains information to get you started creating a mobile single sign-on app or converting an application to a mobile single sign-on app. To serve as a mobile single sign-on agent, the app must include logic to handle authentication requests coming from other apps (the mobile SSO clients).

Follow these steps to initialize and configure the SDK.

  1. Introduce the following instance variable to the class implementing OMMobileServiceDelegate:

    BOOL _setupDone; //Indicates if the application profile was downloaded successfully
    NSString *_ssoAppBundleID; //Store the bundle ID of the SSO client app
    NSURL *_ssoRequestURL; // Stores the request URL sent by the client app
    BOOL _profileError; //Indicates if an error occurred in the profile download
    NSDictionary *_queryParams; // Stores query parameters from the SSO request URL
    
  2. Add the following methods to the same class:

    /* This method is the entry point to handle SSO requests. If the app Profile is not downloaded, it starts the download or it starts by processing the request.
    The App profile download can be triggered from this function if it is not being checked every time the app becomes active. */
    
    - (void) handleRequestWithURL:(NSURL *)url bundleID:(NSString *)appBundleID
    {
        if (!_setupDone)
        {
            self.ssoRequestURL = url;
            self.ssoAppBundleID = appBundleID;
            return;
        }
        [self ssoRequestWithURL:url fromApp:appBundleID];
    }
    
    /* This function invokes the SDK to process the SSO request. */
    
    - (void)ssoRequestWithURL:(NSURL *)url fromApp:(NSString *)appBundleID
    {
        if(_profileError)
        {
            _profileError = FALSE;
            self.ssoAppBundleID = nil;
            self.ssoRequestURL = nil;
            return;
        }
        NSDictionary *params = [self.mobileServices parseURL:url fromApp:appBundleID];
        self.ssoRequestURL = nil;
        self.ssoAppBundleID = nil;
        self.queryParams = params;
    
        /* If this is an SSO request coming from either a native app or a browser
         * then do the SSO flow. Else do application specific logic. */
    
        if ([self.mobileServices isSSORequest:self.queryParams])
        {
            [self.mobileServices processSSORequest:self.queryParams presenter:self]; //It is assumed that the class also extends UIViewController.
        }
    }
    
  3. Add the following code to the didReceiveApplicationProfile:error method:

        if (error)
        {
            _profileError = TRUE;
        }
        else
        {
            _setupDone = TRUE;
        }
     if(self.ssoRequestURL != nil && self.ssoAppBundleID != nil)
        {
            [self ssoRequestWithURL:self.ssoRequestURL fromApp:self.ssoAppBundleID];
            return;
        }
    
    
  4. Add the following code to the didFinishAuthentication:error method:

    if([self.mobileServices isSSORequest:self.queryParams])
        {
            [self dismissModalViewControllerAnimated:NO];
            [error retain];
            [self performSelector:@selector(completeSSOAuthentication:)
                       withObject:(id)error afterDelay:0]; /* This is required because the SSO Agent app  starts the client app registration after authentication. The registration should occur in the next run loop cycle.*/
            return;
        }
    - (void)completeSSOAuthentication:(id)object
    {
        NSError *error = (NSError *)object;
        [self.mobileServices completeSSORequest:self.queryParams presenter:self error:error];
    }
    
  5. Add the following code to the didFinishRegistration:error method:

        [registrationHandle retain];
        [self dismissModalViewControllerAnimated:true];
        [self.mobileServices sendSSOResponseWithHandles:registrationHandle error:loginError params:self.queryParams];
        [registrationHandle release];
    
  6. Add the following to the application:openURL:sourceApplication:annotation method of UIApplicationDelegate :

    /* This starts the SSO request handle process. You can check the request URL to make sure it is an SSO request. */
    
        [<object of class implementing handleRequestWithURL:bundleID method> handleRequestWithURL:url bundleID:sourceApplication];
    

The following is a sample implementation of application:openURL:sourceApplication:annotation:

- (BOOL) application:(UIApplication *)application
             openURL:(NSURL *)url
   sourceApplication:(NSString *)sourceApplication
          annotation:(id)annotation
{
    self.viewController.isConfigUpdate = false;
    NSString *queryString = [url query];
    NSString *host = [url host];
    if ([queryString hasPrefix:@"oamconfig=true&"])
    {
        //do something
    }
    else if([host isEqualToString:@"settings"])
    {
        //do Something
    }
    else
    {
        [self.viewController handleRequestWithURL:url
                                             bundleID:sourceApplication];
    }
    return YES;
}

Note that the app delegate of the iOS mobile SSO app should implement the openURL method to handle SSO requests coming from other applications. The URL scheme should also be defined in the iOS app and on the Mobile and Social server. Finally, when adding the Application Profile to a Service Domain on the Mobile and Social server, configure the Mobile Single Sign-on (SSO) Configuration attributes (Participate in Single Sign-on and Agent Priority).

Note:

For information about configuring iOS specific settings on the Mobile and Social server, see the following topics in Oracle Fusion Middleware Administrator's Guide for Oracle Access Management:

9.13 Login and KBA View Customization

You can create custom views to get login and knowledge-based authentication (KBA) information from the user. The SDK will present these views to the user as needed. Otherwise, the SDK presents the default native view. The following sections have details.

9.13.1 Implementing Native View Customization

Custom native views should subclass OMAuthView and override some methods described later in this section. When creating custom native views:

  • Subclass OMAuthView.

  • Override the viewLoaded method. If any part of the Remember Credentials feature is enabled then the authData dictionary will contain credentials and user preferences for the feature.

  • Override the retrieveAuthData method. This method should populate the authdata dictionary with user input.

Following is sample code to illustrate this.

MyLoginView.h file
@interface MyLoginView : OMAuthView
   //Declare properties required for getting user input
@end
MyLoginView.m file
@implementation MyLoginView
-(void) viewLoaded
{
   // Get credentials and user preferences from self.authData
}
-(NSDictionary *) retrieveAuthData
{
   // Populate self.authData with user input
}
@end
 

When passing the custom native views to the SDK:

  • Create an OMAuthenticationRequest object.

  • Set the authView and kbaView properties to custom native view objects.

  • Pass the OMAuthenticationRequest object to the mss.startAuthenticationProcess:presentViewController method.

Following is sample code to illustrate this.

// Initialize mss object 
OMMobileSecurityService *mss = [[OMMobileSecurityService alloc] initWithProperties:sdkProps delegate:self];
[mss setup];
//Wait for setup to complete
//Create authentication request
OMAuthenticationRequest *authnReq = [OMAuthenticationRequest alloc] init];
MyLoginView *loginView = [[MyLoginView alloc] init];
MyKBAView *kbaView = [[MyKBAView alloc] init];
authReq.authView = loginView;
authReq.kbaView = kbaView;
[mss startAuthenticationProcess:authnReq presenterViewController:myPresenter];

9.13.2 Implementing Progress View Customization

The progress view shown after the login screen can be customized. The pattern is similar to the Login view customization. The app needs to extend the OMAuthProgressView class and register the instance of the app's implementation in OMAuthenticationRequest. A code snippet is given below:

OMAuthenticationRequest *authReq = [[OMAuthenticationRequest alloc] init];
MyProgressView *myProgressView = [[MyProgressView alloc] initWithFrame:self.view.frame];
authReq.authProgressView = myProgressView;
[myProgressView release];

9.14 Using the Cryptography Module

The cryptography APIs provided by iOS are C APIs that are cumbersome to use. The Mobile and Social iOS Client SDK provides intuitive Objective C APIs for common cryptography tasks that are simple to use. The SDK uses the APIs listed here to protect and store credentials for offline authentication. For detailed information about API methods, please refer to the API documentation included in the SDK download.

The following sections contain high-level summaries of the functionality provided by the cryptography module.

9.14.1 Hashing

Use the hashing capability to get the hash value of a string (typically a password) with an auto-generated random salt. The following API also adds the salt to the output and prefixes the algorithm name to the output. This is suitable for storage and transfer over the network. The generated salt, if requested, can be extracted using the outSalt parameter.

NSString *secret = "mypassword";
NSString *outSalt;
NSError *error;

NSString *hashValue = [OMCryptoService SHA256HashAndBase64EncodeData:[secret
                                                           dataUsingEncoding:
                                                           NSUTF8StringEncoding]
                                                 withSaltOfBitLength:24
                                                           outSalt:&outSalt
                                                           outError:&error];

The hashing capability provides the following functionality:

  • Convenience APIs are provided to perform hashing using the following algorithms SHA1, SHA224, SHA256, SHA384, SHA512

  • A similar set of APIs that operate without a salt are also provided

  • A random salt generation method is available if the salt needs to be stored separately

  • The resulting hash value can be optionally Base64 encoded

  • The algorithm name can be optionally prefixed to the output

  • In addition to the convenience API, a more sophisticated method that can customize all values is also provided:

hashData:withSalt:algorithm:appendSaltToOutput:base64Encode:prefixOutputWithAlgorithmName:outError:

9.14.2 Symmetric Key Encryption/Decryption

This API helps perform symmetric key encryption and decryption of data. The following example helps encrypt a given data using AES algorithm, PKCS7 padding using an auto-generated random symmetric key.

  NSData *plainText = ...
  NSString *outKey;
  NSError *error;
 
  NSString *cipherText = [OMCryptoService encryptData:plainText
                             withSymmetricKeyOfLength:24
                                      outSymmetricKey:&outKey
                                             outError:&error];
 

To decrypt the above cipher text, the following API can be used.

  NSString *plainText = [OMCryptoService decryptData:cipherText
                                    withSymmetricKey:outKey
                                            outError:&error];
 
  • The supported algorithms are AES128 (key sizes 16,24,32), DES (key size 8), 3DES (key size 24).

  • A secure symmetric key generation API is available

  • The resultant cipher text can be optionally Base64 encoded

  • The algorithm name can be optionally prefixed to the output.

  • A more sophisticated method that makes it possible to specify the algorithm, initialization vector, padding, and so on is available:

encryptData:withSymmetricKey:initializationVector:algorithm:padding:mode:base64EncodeOutput:prefixOutputWithAlgorithmName:outError:
 decryptData:withSymmetricKey:initializationVector:algorithm:padding:mode:isInputPrefixedWithAlgorithmName:isInputBase64Encoded:outError:

9.14.3 Asymmetric Key Cryptography

The asymmetric key cryptography APIs that are part of OMCryptoService help with the following operations:

  • Key pair generation and storage in a key chain

  • Sign and verify operations with keys in a key chain

  • Wrap and unwrap operations with keys in a key chain

  • Extraction of the public key from a key chain

  • Deletion of a key pair in a key chain

9.15 Using the Auto Login and the Remember Credentials Features

The Mobile and Social iOS Client SDK provides APIs that can securely store user credentials and play them back to a login server with or without user interaction. Deploy this feature in apps where security is not critically important to make it easier for users to log in. This feature requires at least version 11.1.2.2.0 of the Mobile and Social Client SDK.

To use this feature, the user selects one of up to three option boxes on the login screen. (You can choose to enable one, two, or all three of these options in your app.) If more than one option is selected, the higher priority feature takes precedence. The priority of the options is as follows:


1. Auto Login
2. Remember Credentials
3. Remember User Name Only

So for example, if Auto Login and Remember Credentials are selected, then Auto Login takes priority.

The three options are described as follows:

  • Auto Login - The Mobile and Social iOS Client SDK securely caches the user's credentials and automatically supplies them at the login screen. This option does not require any user interaction to log the user in. The user see a progress screen that provides feedback while authentication is underway.

  • Remember Credentials - The Mobile and Social iOS Client SDK securely caches the user's credentials and auto-fills the user name and password fields on the login screen. The user has to click the Login button to proceed with the authentication process. The user can enter different credentials and make changes to the option boxes if necessary.

  • Remember User Name Only - The Mobile and Social iOS Client SDK securely caches the user name and auto-fills the user name on the login screen. The user has to input the password and click the login button to proceed with the authentication process. The user can enter different user name and make changes to the option boxes if necessary.

The following sections have more details.

9.15.1 Enabling the Auto Login and Remember Credentials Feature

This is a client-side only feature that does not require server configuration to deploy. To enable the features described, the following SDK configuration parameters should be added to your code:

Table 9-4 Auto Login and Remember Credentials Configuration Parameters

Parameter Description

OM_PROP_AUTO_LOGIN_ALLOWED

Boolean value that enables/disables the Auto Login feature.

OM_PROP_REMEMBER_CREDENTIALS_ALLOWED

Boolean value that enables/disables the Remember Credentials feature.

OM_PROP_REMEMBER_USERNAME_ALLOWED

Boolean value that enables/disables the Remember User Name Only feature.


9.15.2 Handling User Preferences

Pass the following properties while initializing the mss object to pre-populate the option boxes with a default value. Only one of the following options can be true. If all the option box states are false, all of the option boxes on the login screen will be empty.

Table 9-5 Configuration parameters used to set the option box default values

Parameter Description

OM_AUTO_LOGIN_DEFAULT

Boolean value that specifies the default value of the "Auto Login" option box.

OM_REMEMBER_CREDENTIAL_DEFAULT

Boolean value that specifies the default value of the "Remember Credential" option box.

OM_REMEMBER_USERNAME_DEFAULT

Boolean value that specifies the default value of the "Remember User name Only" option box.


Persist option box states as key-value pairs in NSUserDefaults. Use the combination of the server URL and the application identifier as a key so that the user preferences for each login connection can be uniquely identified.

9.15.3 Clearing Credentials and Preferences from Mobile Devices

Authentication failure can result if the user credentials were changed since the last login, or if the mobile device is not able to reach the authentication service due to a network or server issue. If authentication fails using the stored credentials, the SDK deletes the stored password (if present) from the keychain. The login page will then either revert to the Remember User Name Only feature, or control will revert to the mobile app using OMMobileService delegate. This decision is based on an SDK-level parameter named OM_PROP_MAX_LOGIN_ATTEMPTS, which is a numeric value that stores how many incorrect attempts for authentication are allowed before control is given back to the mobile app.

The SDK will clear a stored user password from the mobile device in the following scenarios:

  • The user authentication fails (for example, if the server password is no longer valid, the user is blocked, or if the user authentication fails for another reason).

  • The Mobile and Social iOS Client SDK logout method is called

  • A session time-out is detected

The SDK will clear the stored user name, password, and option box states from the mobile device in the following scenario:

  • The Mobile and Social iOS Client SDK logout method is called and the clearRegistrationHandles parameter is set to TRUE

9.15.4 Creating a Custom Login Screen

If you want to create a custom login screen instead of using the basic login view provided by the SDK, you need to subclass OMAuthView and add its object to the current authentication request object so that your custom view will be used for authentication instead of the default view. The Mobile and Social iOS Client SDK uses an authentication data dictionary to set user credentials and option box states. This authentication data dictionary is available as a property to every subclass of OMAuthView. Be sure to read these values and display them properly in the UI elements. Similarly, when submitting user credentials, be sure to read values from the UI elements and set them properly in the authentication data dictionary.

The following table lists the keys that you need to use to access credential properties in the authentication data dictionary.

Table 9-6 Keys used to access credential properties in the data dictionary

Key Description

OM_PROP_AUTO_LOGIN_ALLOWED

Boolean value that enables/disables the Auto Login feature.

OM_PROP_REMEMBER_CREDENTIALS_ALLOWED

Boolean value that enables/disables the Remember Credentials feature

OM_PROP_REMEMBER_USERNAME_ALLOWED

Boolean value that enables/disables the Remember User Name Only feature

OM_AUTO_LOGIN_PREF

Boolean value that specifies the user's preference regarding the Auto Login feature.

OM_REMEMBER_CREDENTIALS_PREF

Boolean value that specifies the user's preference regarding the Remember Credentials feature.

OM_REMEMBER_USERNAME_PREF

Boolean value that specifies the user's preference regarding the Remember User Name Only feature.

OM_USERNAME

String value that specifies the user's user name.

OM_PASSWORD

String value that specifies the user's password.


9.16 Using the Credential Store Service (KeyChain)

The Credential Store service provides APIs to store and retrieve sensitive data using iOS Keychain Services.

Start with the OMMobileSecurityService object and get an OMCredentialStore handle. Use OMCredentialStore to write to and retrieve sensitive data from KeyChainItem.

The following sections contain code snippets that illustrate how to use OMCredentialStore.

9.16.1 Adding a User Name and Password

This example adds a user name and password to a given key in KeyChainItem.

- (void)addCredential:(NSString *)userName pwd:(NSString *)password url:(NSString *)key;

9.16.2 Adding a User Name, Password and Tenant Name

This is a variation of the previous addCredential function.

- (void)addCredential:(NSString *)userName 
                  pwd:(NSString *)password 
           tenantName:(NSString *)tenantName 
                  url:(NSString *)key;

9.16.3 Deleting a Credential

This example deletes the credential from KeyChainItem. Because there is not a true delete operation, the user name and password are instead set to null.

- (void)deleteCredential:(NSString*)key;

9.16.4 Updating a User Name and Password

This example updates the user name and password given the user and key values. Because there is not a true update operation, updateCredential calls addCredential.

- (void)updateCredential:(NSString*)userName pwd:(NSString*)password  url:(NSString*)key; 

9.16.5 Updating a User Name, Password and Tenant Name

This is a variation of the previous updateCredential function.

- (void)updateCredential:(NSString *)userName 
                     pwd:(NSString *)password 
              tenantName:(NSString *)tenantName 
                     url:(NSString *)key;

9.16.6 Getting a User Name and Password

This example retrieves the user name, password, and tenant name for a given key.

- (OMCredential *)getCredential:(NSString*)key;

9.16.7 Storing a Property in KeyChainItem

This example stores a property in KeyChainItem.

- (void)storeProperty: (NSString *)property withKey: (NSString *)key;

9.16.8 Storing Multiple Properties in KeyChainItem

This is a variation of the previous storeProperty function.

- (void)storeProperty: (NSString *)property 
              withKey: (NSString *)key
            withLabel: (NSString *)label
      withDescription: (NSString *)description;

9.16.9 Deleting a Property in KeyChainItem

Deletes a given property store in KeyChainItem. All details stored with the property are deleted.

- (NSError *)deletePropertyWithKey:(NSString *)key

9.16.10 Getting a Property

Returns a property from KeyChainItem.

- (id)getPropertyForKey:(NSString *)key