Follow

Shape Defense Mobile SDK iOS Reference

The Mobile SDK for iOS consists of one main class: APIGuard

 

System Requirements

  • Working iOS development environment
  • Apple Developer account (required for packaging)

Apps that incorporate Mobile SDK require:

  • iOS release:
    • iOS 9 and newer
  • Xcode 11 and newer
  • ARC (Automatic Reference Counting)

Exposed Classes and Protocols

The Mobile SDK iOS has the following exposed classes:

Class
APIGuard
Description
The APIGuard class initializes the framework and decorates requests and responses.
Property

state

Methods

 

Property
state
Syntax

APIGuardState agState = APIGuard.sharedInstance()?.state

Description

This property is set to the current state of the APIGuard. The value is an enum object of type APIGuardState, with four possible states:

  1. APIGuardStateNotReady - initialize() was not yet called
  2. APIGuardStateInProgress - initialize() was called, but did not finish
  3. APIGuardStateReady - APIGuard is ready
  4. APIGuardStateFailed - initialize() was called, but initialization failed

state example (Swift)

if (APIGuard.sharedInstance()?.state == APIGuardState.ready) {
   NSLog("APIGuardState: READY")
}

state example (Objective-c)

if ([[APIGuard sharedInstance] state] == APIGuardStateReady) {
       NSLog(@"APIGuardState: READY");
}

 

Method
sharedInstance
Syntax
+ (nullable APIGuard *)sharedInstance
Description
Returns a shared instance of the main SDK object.
Parameters
None.
Returns
The shared instance of the main SDK object.

 

Method
initializeWithConfigFile:withEnvironment:delegate:
Syntax
- (BOOL)initWithConfigFile:(NSString *)filePath withEnvironment:(NSString *)env delegate:(id<APIGuardDelegate>)agDelegate;
Description
Initializes the Mobile SDK with a configuration file path. Call this function as early as possible; it must be called at least once for Mobile SDK methods to work. SDK initialization creates the resources needed to load current configuration file, schedule configuration updates, and tag SDK events. The return value of this function should not be used to determine whether or not payloads are ready to attach to requests.
Parameters
filePath Fully qualified filepath of the Mobile SDK configuration file.
withEnvironment Name of the environment where Mobile SDK should look for configuration file updates. Environments are defined in the updateURL field (for a single environment) or the updateURLMap field (multiple environments) in the base configuration.
agDelegate Class to implement APIGuardDelegate.
Returns

(BOOL)

YES indicates the SDK successfully initialized.

NO indicates the SDK did not successfully initialize.

 

Method

initializeWithConfigFile:delegate:

Syntax
- (BOOL)initializeWithConfigFile:(nullable NSString *) configFilePath delegate:(id<APIGuardDelegate>)delegate
Description

Initializes the Mobile SDK with a configuration file path. Call this function as early as possible; it must be called at least once for Mobile SDK methods to work. SDK initialization creates the resources needed to load the current configuration file, schedule configuration updates, and tag SDK events. The return value of this function should not be used to determine whether or not payloads are ready to attach to requests.

Note: The environment chosen will always be “default” for this function.

Parameters
configFilePath Fully qualified filepath of the Mobile SDK configuration file.
delegate Class to implement APIGuardDelegate.
Returns

(BOOL)

YES indicates Mobile SDK is ready to start decorating.

 NO indicates SDK was not initialized properly and cannot decorate.

 

Method

transformRequest
(Deprecated in Mobile SDK version 4.0.0. Use getRequestHeaders:body: instead.)

Syntax

- (void)transformRequest:(NSMutableURLRequest *)request;

Description

This function transforms an HTTP request that the app is about to send by adding Mobile SDK payloads (headers) to the outgoing network request and returning the request to the host app for processing.

If Mobile SDK is being used to provide tamper evidence of the request, Shape recommends calling this function after all the parts of the request are finalized.

Parameters
request An NSMutableURLRequest object to decorate with Mobile SDK headers.

 

Method

parseResponse
(Deprecated in Mobile SDK version 4.0.0. Use parseResponseHeaders instead.)

Syntax

- (void)parseResponse:(NSURLResponse *)response;

Description

Transforms the incoming API response that the app has received by removing any Mobile SDK specific headers and returns the response for processing by the host app.

Parameters
response An NSURLResponse object for Mobile SDK to parse.

 

Method

getRequestHeaders:body:

Syntax
- (nullable NSDictionary<NSString *, NSString *> *)getRequestHeaders:(NSString *)url body:(nullable NSData *)body
Description
This function returns the HTTP headers that the app must add to the request. This is an alternative to transformRequest for apps using third party networking libraries.
Parameters
url The full URL of the request.
body The body of the request.
Returns
The dictionary of HTTP headers to add to the request.

 

Method

parseResponseHeaders

Syntax
- (void)parseResponseHeaders:(NSDictionary<NSString *, NSString *> *)headers
Description
This function decodes the HTTP headers that Shape adds to the server response. This is an alternative to parseResponse for apps using third party networking libraries.
Parameters
headers Dictionary of the HTTP response headers.

 

Class

APIGuardDelegate

Description
The APIGuardDelegate class is the delegate provided to the SDK by the app.

Methods

 

Method

checkCertificates

Syntax
- (BOOL)checkCertificates:(nonnull NSURLAuthenticationChallenge*)challenge
Description

Mobile SDK calls this method to let the app check the validity of the certificates when connection is being established to update the configuration file. Shape requires implementing this function; it provides app developers with certificate pinning functionality.

Note: Shape Security recommends using the checkCertificates method whenever possible.

Parameters
challenge Networking library’s challenge object.
Returns

(BOOL)

YES indicates the certificate is good. Continue with the connection.

NO indicates the certificate does not match. Terminate the connection.

Notes
If your app does not implement certificate pinning, add return YES;.


Method

log

Syntax
(void)log:(nonull NSString *)string;
Description

Mobile SDK calls this method when it needs to log a message through the app for debugging purposes. The messages are intended for developers; do not log them to the system log in production apps.

Parameters
string The message to log.
Notes
Optional.

 

Method

didUpdateState (Deprecated)

Syntax
(void)didUpdateState:(APIGuardState)state;
Description

Mobile SDK calls this method when it updates its state during initialization. There are two possible states that can occur, APIGuardStateFailed and APIGuardStateReady.

APIGuardStateFailed means Mobile SDK failed to initialize and will not be able to decorate requests. APIGuardStateReady means that Mobile SDK is ready to start decorating requests.

Parameters
state The current SDK state.
Notes
Optional.

 

Method

initializationSuccess

Syntax
- (void)initializationSuccess;
Description

This callback gets called on Initialization success. SDK will call this on a background thread.

Parameters
None.

 

Method

initializationFailure

Syntax
- (void)initializationFailure:(NSString *)error;
Description

Called when initialization fails. Sends the failure reason that conveys information about when the failed callback happened. This function is called on a background thread. You will get this callback only due to improper base config provisioning at initial integration or a critical non-recoverable error in the field. Please contact your Shape Technical Account Manager (TAM) for additional support.

Parameters
String Failure reason.

 

Appendix: checkCertificates Code Sample

The following code snippet uses the TrustKit API to validate the pinned public key for a configured domain.

Note: This is an example of verifying the public key pinning for Shape Mobile SDK configuration fetch. Please make sure to conform to your organization’s security policies/requirements.
func checkCertificates(_ challenge: URLAuthenticationChallenge) -> Bool {

    guard let serverTrust = challenge.protectionSpace.serverTrust else {
      return false
    }

    let domainName = "mobile-test.fastcache.net"

    let trustKitConfig = [ kTSKPinnedDomains:
                                [ domainName: [kTSKPublicKeyAlgorithms: [kTSKAlgorithmRsa2048],

                                // if set to false, pin failure reports are sent to a report server hosted by Data Theorem by default
                                kTSKDisableDefaultReportUri: true,

                                kTSKPublicKeyHashes: [
                                // Primary Key
                                "4j+7QhRAg9xZaevlP3wQ7jvzsjYBuMidlVD83dl3d54=",

			                          // Backup Key, Can be used in case primary is compromised
                                "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
                                ],]
                          ]] as [String : Any]

    TrustKit.initSharedInstance(withConfiguration:trustKitConfig)

    let pinningValidator = TrustKit.sharedInstance().pinningValidator.evaluateTrust(serverTrust, forHostname: domainName)

    return pinningValidator.rawValue == TSKTrustDecision.shouldAllowConnection.rawValue
  }

 

Related Content

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request